我有一个简单的 .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" });
});
}
Run Code Online (Sandbox Code Playgroud)
当我输入无效 url 时,/error/404.html 会按预期显示,但浏览器会收到 200 状态代码,而不是预期的 404 状态。
我究竟做错了什么?我可以不使用静态 html 文件作为错误页面吗?
当你使用app.UseStatusCodePagesWithReExecute你
添加一个 StatusCodePages 中间件,指定应通过使用备用路径重新执行请求管道来生成响应正文。
由于路径/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>);
}
}
Run Code Online (Sandbox Code Playgroud)
然后将中间件注册为
app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");
Run Code Online (Sandbox Code Playgroud)
在重定向期间,此占位符 {0} 将自动替换为状态代码整数。
| 归档时间: |
|
| 查看次数: |
6866 次 |
| 最近记录: |