ASP.NET MVC throws and processes an error from the controller

In my controller to allow user editing. In my controller, I check if the user has edit rights, then I would like to throw some kind of authentication or a forbidden error that would lead to the error page.

Is there a way to do this, and not create a controller and action just for errors? What is the right way to do this?

+4
source share
2 answers

Here is an example of a custom authorize attribute that you can use:

public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // if the user is not authenticated render the AccessDenied view filterContext.Result = new ViewResult { ViewName = "AccessDenied" }; } } } 

and then decorate your controller action with this attribute:

 [CustomAuthorizeAttribute] public ActionResult SomeAction() { ... } 

Beware of an approach you should be aware of. If the user is not logged in, the server sends 200 status codes that are not very friendly to SEO. It is better to send a 401 status code. The problem is that if you use Forms Authentication, there is a custom module that is added to the ASP.NET execution pipeline and whenever the server sends the 401 status code, it is intercepted and automatically redirected to the login page. This design functionality is not a bug in ASP.NET MVC. It has always been so.

And, in fact, there is a way to overcome this unpleasant situation:

You can change the custom authorization filter as follows:

 public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // if the user is not authenticated render the AccessDenied view filterContext.HttpContext.Items["unauthorized"] = true; } } } 

and in Global.asax:

 protected void Application_EndRequest() { if (Context.Items.Contains("unauthorized")) { Context.Response.Clear(); Context.Response.StatusCode = 401; Context.Server.Transfer("~/401.htm"); } } 

Now it is better. You get a 401 status code with a custom error page. Nice.

+2
source

Since your authorization is user-based (I believe that the correct process is that each user can edit their own data), you cannot use the filter provided by Authorize .

Instead, write a custom authorization filter . You can provide any functionality that you need. It is common to return a 401 HTTP status code.

-1
source

Source: https://habr.com/ru/post/1335433/


All Articles