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

Asp.net core 使用UseStatusCodePagesWithReExecute时,状态代码不会发送到浏览器,asp.net-core,Asp.net Core,我有一个简单的.NETCore2.0项目。以下是配置方法: public void Configure(IApplicationBuilder app, IHostingEnvironment environment) { app.UseStatusCodePagesWithReExecute("/error/{0}.html"); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute(

我有一个简单的.NETCore2.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" });
    });
  }
当我输入一个无效的url时,/error/404.html将按预期显示,但浏览器将获得一个200状态代码,而不是预期的404状态


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

当您使用
app.UseStatusCodePagesWithReExecute

添加StatusCodePages中间件,该中间件指定应通过使用alternate重新执行请求管道来生成响应正文 路径

当路径
/error/404.html
存在且工作正常时,使用200状态


您可以使用以下方法(查看更多详细说明):

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

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>);
    }
}

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

UseStaticFiles在提供404.html时可能会设置为200。你可以在选项的事件中覆盖它。谢谢,这个答案帮了我一点忙。但是有可能从ErrorController重定向到静态404.html吗?如果在我的原始问题中不清楚,“error”是“wwwroot”中的一个目录,而不是控制器,“404.html”是wwwroot/error目录中的一个html文件。@bjarteaunolsen:已编辑答案,因此操作现在返回一个静态文件而不是视图(查看)。您不需要使用重定向,因为您将再次看到200 OK=>重定向的工作方式如下:服务器发送302代码和位置头,浏览器请求由位置头指定的新URI。方法文件(字符串文件路径)似乎不存在于dotnet core中,所以我会继续使用你在第一个答案中建议的视图。@Bjaretauneolsen好的,现在有了一个方法。只需指定“text/html”作为内容类型。
app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");