Reputation: 4517
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
? 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. Is this a bug or is this by design?
Upvotes: 1
Views: 53
Reputation: 46551
Error handling is not the responsibility/concern of the MVC middleware. 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. For example:
public void Configure(IApplicationBuilder app)
{
app.UseExceptionHandler("/path/to/error/page");
app.UseMvc();
}
Upvotes: 2
Reputation: 8662
The 500 status code is set by the ASP.NET middleware before the exception is returned to the caller. If you test your API with Postman you will see it reports a Status Code 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.
As an experiment add the UseDeveloperExceptionPage()
code to 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(...
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. It depends where your code is in the pipeline as to what status code it sees.
Upvotes: 2