Skip to main content
edited title
Link
tmg
  • 20.6k
  • 5
  • 75
  • 79

Prevent error page action executing directly from a request - ASP.NET-Core

Source Link
tmg
  • 20.6k
  • 5
  • 75
  • 79

Prevent error page action executing directly from a request - ASP.NET-Core

In asp.net-core we can show user-friendly error pages by adding the StatusCodePages middleware to the pipeine. In Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // code ... app.UseExceptionHandler("/error/500"); app.UseStatusCodePagesWithReExecute("/error/{0}"); // code ... } 

With above code, when an unhandled exception occurs or a requested resource can not be found, the responses is handled by redirecting to /error/{0}. Framework correctly invokes this action

[Route("[controller]")] public class ErrorController : Controller { [HttpGet("{statusCode}")] public IActionResult Error(int statusCode) { Response.StatusCode = statusCode; return View("Error", statusCode); } } 

The problem starts when client directly requests something like ~/error/{int}. For example www.example.com/error/500 or www.example.com/error/400

In these cases again the above action is being invoked (from MVC not StatusCodePages middleware) and client gets a 500 and a 400 response. In my opinion, 404 status code must be returned for all ~/error/{int} requests.

Is there any solution, when client makes a ~/error/{int} request to prevent MVC middleware from invoking the error action?