Reputation: 20393
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?
Upvotes: 3
Views: 937
Reputation: 141532
Use HttpContext.Features.Get<IExceptionHandlerFeature>()
to check whether an error has occurred. If one hasn't, then return a 404. Here is an example.
ErrorController.cs
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Http.Features;
using Microsoft.AspNet.Mvc;
[Route("[controller]")]
public class ErrorController : Controller
{
[HttpGet("{statusCode}")]
public IActionResult Error(int statusCode)
{
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (feature == null || feature.Error == null)
{
var obj = new { message = "Hey. What are you doing here?"};
return new HttpNotFoundObjectResult(obj);
}
return View("Error", statusCode);
}
}
According to the docs (emphasis added),
The HttpContext type... provides an interface for getting and setting these features... Use the pattern shown above for feature detection from middleware or within your application. Calls made to GetFeature will return an instance if the feature is supported, or null otherwise.
Upvotes: 5