简体   繁体   English

为什么发生异常时未从Mvc设置StatusCode

[英]Why is StatusCode not set from Mvc when exception occurs

In a simple application: 在一个简单的应用程序中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        try
        {
            await next();
        }
        finally
        {
            var test = context.Response.StatusCode;
            //test=200 when exception is thrown from Mvc()
        }
    });
    app.UseMvc();
}

Why is the Response.StatusCode not set if a controller throws an Exception ? 如果控制器抛出Exception为什么未设置Response.StatusCode This seems quite surprising and undocumented. 这似乎很令人惊讶,没有记载。 It seems to work inconsistent with the concept of the pipeline where eg. 这似乎与管道的概念不一致,例如。 401 and 404 have been set at this point. 此时已设置401404 Is this a bug or is this by design? 这是错误还是设计使然?

Error handling is not the responsibility/concern of the MVC middleware. 错误处理不是MVC中间件的责任/关注点。 The exception will just bubble up and other middleware (such as developer exception page or exception handler) should handle this error. 异常只会冒出来,其他中间件(例如开发人员异常页面或异常处理程序)应该处理此错误。

You can try this by adding UseDeveloperExceptionPage() or UseExceptionHandler() before the UseMvc() call. 您可以通过在UseMvc()调用之前添加UseDeveloperExceptionPage()UseExceptionHandler() 进行 UseMvc() For example: 例如:

public void Configure(IApplicationBuilder app)
{
    app.UseExceptionHandler("/path/to/error/page");
    app.UseMvc();
}

The 500 status code is set by the ASP.NET middleware before the exception is returned to the caller. 在将异常返回给调用者之前,ASP.NET中间件设置了500状态代码。 If you test your API with Postman you will see it reports a Status Code 500. 如果使用Postman测试您的API,您会看到它报告状态码500。

The reason you do not see it in your example is because your async function is further up the pipeline than the code that detects the exception and returns the 500 status code. 在您的示例中看不到它的原因是,与检测异常并返回500状态代码的代码相比,您的异步功能在管线的上游。

As an experiment add the UseDeveloperExceptionPage() code to Configure 作为实验,添加UseDeveloperExceptionPage()代码以进行Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Use(async (context, next) =>
    {
        try
        {
            await next();
        }
        finally
        {
            var test = context.Response.StatusCode;
        }
    });

    app.UseMvc();
}

When you run with this code the StatusCode is 500. However, if you move the code to AFTER the app.Use(... 使用此代码运行时,StatusCode为500。但是,如果将代码移至应用程序之后app.Use(...

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context, next) =>
    {
        try
        {
            await next();
        }
        finally
        {
            var test = context.Response.StatusCode;
        }
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();
}

In this code you will find that the StatusCode is 500. So it's all about the middleware setting the correct status code. 在此代码中,您将发现StatusCode为500。因此,所有关于中间件设置正确状态代码的信息。 It depends where your code is in the pipeline as to what status code it sees. 这取决于代码在管道中的位置以及所看到的状态代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发生异常时无法显示MVC错误视图 - Cannot display mvc error view when exception occurs 为什么 grpc unhandled (StatusCode="Unavailable"), 在调用从 proto 文件生成的方法时未知? - why grpc unhandled (StatusCode="Unavailable") ,unknown when invoking a method generated from a proto file? 发生异常时启动表格 - Starting a Form when an Exception occurs 发生参数Exception时重定向 - Redirecting when an argument Exception occurs 当我在静态构造函数中发生异常时,为什么Visual Studio不显示异常消息? - Why doesn't Visual Studio show an exception message when my exception occurs in a static constructor? 在ASP.NET MVC中发生NullReferenceException异常时在浏览器中创建错误消息 - Create error message in browser when NullReferenceException exception occurs in asp.net mvc 使用自定义状态码抛出异常 - throw an exception with custom statuscode 当端点分发程序的消息检查器中发生未处理的异常时,为什么WCF IErrorHandler表现怪异? - Why does a WCF IErrorHandler behave weird when an unhandled exception occurs in a endpoint dispacher's message inspector? 当 IXmlSerializable.ReadXml() 内发生架构验证错误时,为什么 XmlSerializer 会抛出异常并引发 ValidationEvent - Why does XmlSerializer throws an Exception and raise a ValidationEvent when a schema validation error occurs inside IXmlSerializable.ReadXml() 即使对象不为null,也会发生NullReference异常 - NullReference exception occurs even when the object is not null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM