Search code examples
c#.net-coremodel-view-controllerredirecttoactionaspnetcore-environment

How to call RedirectToAction in asynchronous Task methods?


I am using MVC aspnetcore dotnetcore 6.0

I do an authorization with a LoginController. When it is success i want to redirect the user into HomeController. But RedirectToAction does not work. My code is here:

[HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> UserLoginAsync(LoginRequestModel requestModel)
    {
        try
        {
            if (ModelState.IsValid)
            {
                LoginResponseModel loginResponseModel = new LoginResponseModel();
                var res = _wrapperService.Post<LoginRequestModel, LoginResponseModel>(requestModel, "/api/auth/login");
                var tokenRes = GetTokenInfo(res.Result.Data.Token);

                HttpContext.Session.SetString("username", requestModel.Email);
                var userIdentity = new ClaimsIdentity(tokenRes, "Login");
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(userIdentity);
                await HttpContext.SignInAsync(claimsPrincipal);
                return RedirectToAction("Index", "Home"); // I want to redirect this but it does not work. 
                return Ok(res.Result);
            }

            return BadRequest(ModelState);
        }
        catch (Exception e)
        {
            var errors = new HttpErrorViewModel()
            {
                Errors = new List<string>()
            };
            errors.Errors.Add(e.InnerException.Message);
            return BadRequest(errors);
        }
        
    }

My Ajax code here:

function LoginWithMail() {
        var inputs = {};
        $("#form-login .input-login").each(function () {
            inputs[$(this)[0].name] = $(this)[0].value;
        });
        $.ajax({
            method: "POST",
            url: "/Login/UserLogin/",
            data: inputs,
            dataType: 'json',
            beforeSend: function () {
                $("#Email").removeClass("border border-danger");
                $("#Password").removeClass("border border-danger");
                $("#LoginSpinner").show();
                $("#loginResMessages").html("").removeClass();
            },
            success: function (res) {
                console.log(res);
                $("#LoginSpinner").hide();

            },
            error: function (xhr, status, error) {
                $("#LoginSpinner").hide();

                $("#loginResMessages").html("");

I repeat. I want to redirect this code when it is success. I tried many solutions i found but not worked too. Please help.


Solution

  • Did you send request to login action with ajax? It can be a problem.

    If did you send post request with ajax, just handle the response inside ajax method. If it is success, change the window location to home/index with js.