asp.net-core - 使用 UseStatusCodePagesWithReExecute 时,状态代码不会发送到浏览器

标签 asp.net-core

我有一个简单的 .NET Core 2.0 项目。这是配置方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment environment)
{
  app.UseStatusCodePagesWithReExecute("/error/{0}.html");

  app.UseStaticFiles();

  app.UseMvc(routes =>
  {
    routes.MapRoute(
      name: "default",
      template: "{controller}/{action?}/{id?}",
      defaults: new { controller = "Home", action = "Index" });
    });
  }

当我输入无效网址时,/error/404.html 按预期显示,但浏览器收到 200 状态代码,而不是预期的 404 状态。

我做错了什么?我可以不使用静态 html 文件作为错误页面吗?

最佳答案

当您使用app.UseStatusCodePagesWithReExecute时,您

Adds a StatusCodePages middleware that specifies that the response body should be generated by re-executing the request pipeline using alternate path.

由于路径 /error/404.html 存在并且工作正常,因此使用 200 状态。

<小时/>

您可以使用以下方法(查看 this article 以获取更详细的说明):

设置操作将根据作为查询参数传递的状态代码返回 View

public class ErrorController : Controller  
{
    [HttpGet("/error")]
    public IActionResult Error(int? statusCode = null)
    {
        if (statusCode.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = statusCode.Value;
        }

        //return a static file. 
        return File("~/error/${statusCode}.html", "text/html");

        // or return View 
        // return View(<view name based on statusCode>);
    }
}

然后将中间件注册为

app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");

此占位符 {0} 将在重定向期间自动替换为状态代码整数。

关于asp.net-core - 使用 UseStatusCodePagesWithReExecute 时,状态代码不会发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373668/

相关文章:

c# - 防止 AddRedirectToWwwPermanent() 在 ASP.NET Core 2.1 中将 "www"添加到 *.azurewebsites.net 前面

c# - AspNet Core 集成测试,将参数传递给 WebApplicationFactory

azure - 在 Azure Web 应用程序中显示 ASP.NET 5 错误页面

c# - 如何测试返回 Ok(object) 的 ASP.NET Core 2.2 Web API GET IActionResult?

asp.net-core - 如何在ASP.NET Core中启动Quartz?

c# - 如何为 Asp.net 核心 OData api 启用 swagger

c# - 如何使用 ASP.NET 5 运行 Firebird 嵌入式数据库?

asp.net-core - Modelbinder 在返回 null 时默认为 0 而不是 Controller 中设置的值

docker - 无法从Docker容器打开URL

c# - 无法访问已处置的对象。对象名称 : 'IServiceProvider' error in AspNet Core/EF Core project