Description
Is this a Bug or Feature request?:
Feature Request / Question
Steps to reproduce or link to a repro project:
[ApiController]
[Produces("application/json")]
[Route("api/v1/value")]
public class ValueApiController : Controller
{
[HttpGet]
public ActionResult<string[]> Get()
{
throw new Exception("bam");
}
}
Startup.cs
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseStatusCodePagesWithReExecute("/Error");
}
Description of the problem:
When an error occurs in Controller classes marked with [ApiController]
, I don't want them to return HTML but JSON instead:
-
In development, instead of Developer Exception Page, ideally the API Controller should return stack trace in plain text / JSON.
-
In production, instead of a custom HTML error response, ideally the API Controller should return a plain text / JSON with like
"An error occurred while processing your request."
When using Core MVC < 2.1, I have been able to do this by using code like:
app.UseWhen(context => context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase), builder =>
{
builder.UseExceptionHandler(configure =>
{
configure.UseMiddleware<ApiExceptionHandlerMiddleware>(env.IsDevelopment());
});
});
app.UseWhen(context => context.Request.Path.Value.StartsWith("/api", StringComparison.OrdinalIgnoreCase) == false, builder =>
{
if (env.IsDevelopment())
{
builder.UseDeveloperExceptionPage();
}
else
{
builder.UseExceptionHandler("/error");
builder.UseStatusCodePagesWithReExecute("/error");
}
});
However, seeing that the purpose of the [ApiController]
is: (written on the XML doc)
Indicates that a type and all derived types are used to serve HTTP API responses. The presence of this attribute can be used to target conventions, filters and other behaviors based on the purpose of the controller.
, I would like to know how to alter the error behavior when this attribute is encountered. (Instead of checking whether the request starts with /api
)
Version of Microsoft.AspNetCore.Mvc
or Microsoft.AspNetCore.App
or Microsoft.AspNetCore.All
:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.0-rc1-final" />