[英]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. 此时已设置401和404 。 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.