我有一个简单的 .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/