在asp.net-core中,我们可以通过将StatusCodePages中间件添加到管道来显示用户友好的错误页面。在Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// code ...
app.UseExceptionHandler("/error/500");
app.UseStatusCodePagesWithReExecute("/error/{0}");
// code ...
}
使用上面的代码,当发生未处理的异常或找不到请求的资源时,响应将通过重定向到/error/{0}
来处理。框架正确调用此操作
[Route("[controller]")]
public class ErrorController : Controller
{
[HttpGet("{statusCode}")]
public IActionResult Error(int statusCode)
{
Response.StatusCode = statusCode;
return View("Error", statusCode);
}
}
当客户端直接请求~/error/{int}
之类的内容时,问题就开始了。例如www.example.com/error/500
或www.example.com/error/400
在这些情况下,再次调用上述操作(来自MVC而不是StatusCodePages中间件),客户端获得500和400响应。在我看来,必须为所有~/error/{int}
个请求返回404状态代码。
当客户端发出~/error/{int}
请求以阻止MVC中间件调用错误操作时,是否有任何解决方案?
答案 0 :(得分:4)
使用HttpContext.Features.Get<IExceptionHandlerFeature>()
检查是否发生了错误。如果没有,则返回404.这是一个例子。
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(强调补充),
HttpContext类型...提供了获取和设置这些功能的界面...... 使用上面显示的模式进行功能检测来自中间件或。如果支持该功能,则对GetFeature的调用将返回实例,否则返回null。