How to redirect to /Home from server side after logged in?

Dondon510 261 Reputation points
2022-04-11T02:41:42.607+00:00

How to redirect to /Home from server side after logged in?

startup.cs

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

User/Login controller

[HttpPost]
        [Route("/User/Login")]
        [AllowAnonymous]

        public JsonResult Login(string user_code, string password, string tenant_code, string _return_url)
        {
            JsonResult _ret = Json(new { result = false, message = "Bad request", http_code = 401 });

            string _api_key = Request.Headers["api_key"].ToString();
            string _api_secret = Request.Headers["api_secret"].ToString();

            if (_api_key != Models.AppSettingsModel.Application.API_Key || _api_secret != Models.AppSettingsModel.Application.API_Secret)
            {
                return Json(new { result = false, message = "Unauthorized", http_code = 401 });
            }

            if (user_code == 'test' && password == '1234')
            {
                   _ret = Json(new { result = true, message = "Login succeed", http_code = 200});
             }

return _ret

Home Controller

 public IActionResult Index()
        {
            return View();
        }

Javascript:

                   const params = $('#form-data').serialize();

                    ajaxCallPostWithHeaders('@Url.Action("Login", "User")', params, headers, function (result) {
                        if (result.result == true) {
                            _userObj = result.payload.data;
                             $.ajax({
                                 type: 'GET',
                                 url: '/Home/',
                                data: {  }
                            });
                        } else showError(result.message, 'PTHelper');
                    });
Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

5 answers

Sort by: Most helpful
  1. Anonymous
    2022-04-11T08:02:10.437+00:00

    Hi @Dondon510 ,

    How to redirect to /Home from server side after logged in?

    According to your code, since you are using JavaScript to call the login method, after calling the login method success, to redirect to the home page, you could use the window.location.href property, like this:

                     ajaxCallPostWithHeaders('@Url.Action("Login", "User")', params, headers, function (result) {  
                         if (result.result == true) {  
                             _userObj = result.payload.data;  
    
                            //redirect to Home page.  
                            // window.location.href ="/Home";  
    
                            //based on your comment to change the code as below:  
                             window.location.href ="/prime/test/v1/Home";  
    
                         } else showError(result.message, 'PTHelper');  
                     });  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

  2. Dondon510 261 Reputation points
    2022-04-11T08:43:41.06+00:00

    Hi,

    this is related to my previous question about deployment sub-folder (/prime/test/v1 --> CentOS 7), if I use this window.location.href ="/Home"; it will goes to https://example.com/Home instead of https://example.com/prime/test/v1/Home


  3. Dondon510 261 Reputation points
    2022-04-11T13:24:19.103+00:00

    it doesn't work as expected, it returns to login page again!

    user will first go to this GET below

            [HttpGet]
            [Route("/User/Login")]
            [AllowAnonymous]
            public IActionResult Login(string ReturnUrl = null)
            {
                if (Url.IsLocalUrl(ReturnUrl))
                    ViewData["ReturnUrl"] = ReturnUrl;
                else
                    ViewData["ReturnUrl"] = "Home";
    
             return View(ViewData);
    }
    

    when theyclick a login button, they go to the following javascript

    javascript

                     ajaxCallPostWithHeaders('@Url.Action("Login", "User")', params, headers, function (result) {
                            if (result.result == true) {
                                window.location.href = "/prime/test/v1/Home";          ---> I expect here they can go to /Home
    
                            } else showError(result.message, 'PTHelper');
                        });
    

    then call controller user -> login POST

            [HttpPost]
            [Route("/User/Login")]
            [AllowAnonymous]
              public JsonResult Login(string user_code, string password)
              { 
                    return Json(new { result = true, message = "OK for dev only", http_code = 200 });
              }
    

  4. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2022-04-12T19:34:48.477+00:00

    most likely the login button is performing a form submit in addition to the click event.


  5. Dondon510 261 Reputation points
    2022-04-13T00:53:48.397+00:00

    @Bruce (SqlWork.com)

    what I have in my html are only this (sorry, I'm quite new as front-end developer, I'm taking over the task), what did I do wrong?

                          <form id="form-data" method="post" autocomplete="off" novalidate="novalidate">  
                                 ...  
                                 ...  
                                    <button type="submit" class="btn btn-success btn-lg btn-block btn-ladda mb-3" asp-controller="user" asp-action="login">Log In</button>  
      
                                     ...  
                                    ...  
                                     
      
                                </form>  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.