ASP.NET MVC4 error handling for 404, 401 and other exceptions

I am trying to figure out how to handle errors correctly in ASP.NET MVC4. As an example, I created a new MVC4 project using the "Internet Application" template and updated my home controller to check for some errors:

public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Hello"; return View(); } public ActionResult About() { throw new HttpException(401, "Not Authorized"); } public ActionResult Contact() { throw new Exception("Oh no, some error occurred..."); } } 

I included customErrors in my web.config file:

 <customErrors mode="On"></customErrors> 

When I launch the application and click on "Contact", I see the view ~ / Views / Shared / Error.cshtml, as expected, since I have a HandleErrorAttribute registered as a global filter.

However, when I click β€œO”, I get a standard ASP.NET error page that says β€œRuntime Error”. Why are these two exceptions handled differently and how can I get HttpException instances to be caught using the HandleError attribute?


CustomErrors Configuration

Ideally, I would like custom error pages to display as follows:

  • User page 404 (not found), which is convenient and user friendly.
  • User 401 (unauthorized) page informing the user that they do not have access (for example, after checking permissions for a specific element in the model)
  • A common error page that is used in all other cases (instead of the standard yellow ASP.NET page).

I created a new Error controller with views for each of the scenarios described above. Then I updated customErrors in web.config as follows:

 <customErrors mode="On" defaultRedirect="~/Error/Trouble"> <error statusCode="404" redirect="~/Error/NotFound"></error> <error statusCode="401" redirect="~/Error/NotAuthorized"></error> </customErrors> 

Page 404 works fine, but I don't get page 401 at all . Instead, I get the view ~ / Error / Trouble (the one that is specified as defaultRedirect ) when I try to access the About action on the Home controller.

Why is my custom 401 redirect page not working?

+4
source share
3 answers

ASP.NET uses 401 internally to redirect users to the login page. Wherever you want to throw 401 unauthorized, throwing 403 instead is prohibited.

+15
source

If you really need to return 401, not 403, you can use:

 HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true 
+8
source

I had a similar problem when I could not get 401 errors to go to my page, despite the change in web.config.

For 401, you are likely to see the standard 401 Unauthorized page, even if you added 401 to the customerrors section in your web.config. I read that when using IIS and Windows authentication, verification happens before ASP.NET even sees the request, so you see its own 401.

In my project, I edited the Global.asax file to redirect to the route that I created for 401 errors, sending the user to the "Unauthorized to see this" view.

At Global.asax:

  void Application_EndRequest(object sender, System.EventArgs e) { // If the user is not authorised to see this page or access this function, send them to the error page. if (Response.StatusCode == 401) { Response.ClearContent(); Response.RedirectToRoute("ErrorHandler", (RouteTable.Routes["ErrorHandler"] as Route).Defaults); } } 

and in Route.config:

  routes.MapRoute( "ErrorHandler", "Error/{action}/{errMsg}", new { controller = "Error", action = "Unauthorised", errMsg = UrlParameter.Optional } ); 

and in the controller:

  public ViewResult Unauthorised() { //Response.StatusCode = 401; // Do not set this or else you get a redirect loop return View(); } 
+4
source

All Articles