使用UseStatusCodePagesWithReExecute时,状态代码不会发送到浏览器 [英] When using UseStatusCodePagesWithReExecute, statuscode is not sent to browser

查看:893
本文介绍了使用UseStatusCodePagesWithReExecute时,状态代码不会发送到浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple .NET Core 2.0 project. Here is the Configure method:

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状态.

When I enter an invalid url, /error/404.html is displayed as expected, but the browser gets a 200 status code, instead of the expected 404 status.

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

What am I doing wrong? Can I not use a static html file as error page?

推荐答案

使用app.UseStatusCodePagesWithReExecute

添加一个StatusCodePages中间件,该中间件指定应使用替代方法通过重新执行请求管道来生成响应主体 路径.

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状态.

As path /error/404.html exists and works OK, the 200 status is used.

您可以使用以下方法(查看

You may use the following approach (look into this article for more detailed explanation):

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

setup action that will return View based on a status code, passed as a query parameter

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}将在重定向期间自动替换为状态码整数.

this placeholder {0} will be replaced with the status code integer automatically during redirect.

这篇关于使用UseStatusCodePagesWithReExecute时,状态代码不会发送到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆