2017-09-22 329 views
1

我有一个简单的.NET Core 2.0项目。下面是配置方法:当使用UseStatusCodePagesWithReExecute,状态码不会发送到浏览器

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文件作为错误页面吗?

+0

UseStaticFiles可能会在服务于404.html时设置200。你可以在选项中覆盖它。 – Tratcher

回答

0

当您使用您app.UseStatusCodePagesWithReExecute

添加一个StatusCodePages中间件,它指定在响应正文应该通过重新执行请求流水线使用替代 路径来生成。

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


您可以用下面的办法(考虑this article了更详细的解释):

设置的行动,将根据状态代码返回查看,作为查询参数

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

此pl在重定向期间,aceholder {0}将被状态码整数替换。

+0

谢谢,这个答案帮了我更多一点。但是有可能从ErrorController重定向到我的静态404.html? –

+0

如果在我原来的问题中还不清楚,“error”是“wwwroot”中的一个目录,而不是控制器,“404.html”是wwwroot/error目录中的html文件。 –

+0

@BjarteAuneOlsen:编辑了答案,现在该动作返回静态文件而不是视图(请参阅https://github.com/aspnet/Mvc/issues/3751)。您不需要 需要使用重定向,因为您将再次看到200 OK =>重定向的工作方式如下:服务器将302代码与Location标头一起发送,并且浏览器请求由Location标头指定的新URI代替。 – Set