2

I have ASP.NET Core 2 MVC project. I am posting some data using JQuery to action. Suppose User.Identity.Name is null and I want to redirect to AccountController AccessDenied action. I am unable to use RedirectToAction (also removed return). Because this goes back to JQuery success/error.

Is there any solution to this?

IN Controller

if (string.IsNullOrEmpty(User.Identity.Name))
    return RedirectToAction(nameof(AccountController.AccessDenied), "Account");

In My JS

$.ajax({
        type: "POST",
        url: '/MyController/MyAction',
        dataType: "json",
        data: $(this).serialize(),
        success: function (data, status, xhr) {

        },
        error: function (xhr, status, err) {
            errorAlert(xhr.responseText, "ERROR");
        }
    });

2 Answers 2

2

so here is the deal when you do an ajax call it expects a return value and hence you cannot redirect an ajax call from the server side but you can do one thing u can send the url as string to which you want to redirect and then redirect it from client side ie

if (string.IsNullOrEmpty(User.Identity.Name))
    return "YourController/YourAction/ParamifAny";

and in controller side

$.ajax({
        type: "POST",
        url: '/MyController/MyAction',
        dataType: "json",
        data: $(this).serialize(),
        success: function (data, status, xhr) {
         window.location.href = data
        },
        error: function (xhr, status, err) {
            errorAlert(xhr.responseText, "ERROR");
        }
    });
Sign up to request clarification or add additional context in comments.

2 Comments

This is not full code. I use success in JQuery as well to reload stuff. So can not use it for href :(
you can pass in an object instead of string n which a bool status if status is true then dont redirect else redirect
1

Let Ajax error function to redirect when server response is access denied.

error: function (xhr, status, err) {
    if(xhr.status==401) {
        window.location.replace('@Url.Action("AccessDenied", "Account")');
    } else {
        errorAlert(xhr.responseText, "ERROR");
    };
}

From controller return http error 401, so that it will trigger error Ajax function at client.

return Unauthorized();

1 Comment

there is a catch then what if something else go wrong like server not answering or 404 action even then it will go to error block aint it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.