【问题标题】:Prevent error page action executing directly from a request防止直接从请求执行错误页面操作
【发布时间】:2016-04-12 09:41:29
【问题描述】:

在 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/500www.example.com/error/400

在这些情况下,上述操作再次被调用(来自 MVC 而不是 StatusCodePages 中间件)并且客户端收到 500 和 400 响应。在我看来,所有~/error/{int} 请求都必须返回404 状态码。

当客户端发出~/error/{int}请求以防止MVC中间件调用错误操作时,有什么解决方案吗?

【问题讨论】:

  • 尝试向标准 MVC 路由控制器添加“约束”以绕过“错误”控制器。另一种可能性可能是使错误控制器只能由内部进程访问,而不是用户。
  • 你为什么关心用户是否直接向 ~/error/500 发出请求?
  • @SRQCoder 如果我使用路由约束,那么我根本不会得到错误页面。我不确定如何实施您的第二个建议。

标签: error-handling asp.net-core


【解决方案1】:

使用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。

【讨论】:

    猜你喜欢
    • 2010-11-05
    • 2010-09-16
    • 1970-01-01
    • 2011-09-10
    • 2014-03-31
    • 2020-06-21
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多