My MVC web application serves two types of users.
Additionally,
When users access the application, if they are not logged in, the application should react differently.
I'm used to working with WCF REST service where I could raise an exception like this:
throw new WebProtocolException(System.Net.HttpStatusCode.Unauthorized, exc.Message, exc);
and receive a 401 message. The problem with the same approach within MVC when I put the statusCode
like this:
HttpContext.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized
it always redirects to the LogIn page.
How can I do this?
I've tried overriding the AuthorizeAttribute
and handling the OnAuthorization
function, but still as soon as I set the statusCode
to 401 it gets redirected to the LogIn page.
If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.
Authorization in MVC is controlled through the AuthorizeAttribute attribute and its various parameters. At its simplest applying the AuthorizeAttribute attribute to a controller or action limits access to the controller or action to any authenticated user.
You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.
To prevent login page redirection you must set SuppressFormsAuthenticationRedirect
property of HttpContext.Response
to true;
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With