I'm adding some web API methods to an existing ASP.NET Core web app. This means my new web API controller(s) will have the attribute [ApiController] and calling clients will expect the return output to be JSON instead of regular HTML.
In another project, I implement a custom exception handler using app.UseExceptionHandler(...) which encodes the response in JSON, giving information about the exception. In this one, I want to do that, but only when the exception came from an action method inside an [ApiController] controller; otherwise I still want to use app.UseExceptionHandler("/Home/Error");, as the exception came from a regular page and the response should be HTML.
Is there a way I can set up an exception handler so that it knows where the exception came from, and render the response accordingly?
May I know which version are you using ASP.Net Core? link might be helpful for you. Exception Handler Middleware for ASP.Net Core Web Api
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var detail = context.Error.StackTrace;
var message = context.Error.Message;
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
ExceptionMessage = "File error thrown";
_logger.LogError(ExceptionMessage);
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
ExceptionMessage += " from home page";
}
In this one, I want to do that, but only when the exception came from an action method inside an [ApiController] controller; otherwise I still want to use app.UseExceptionHandler("/Home/Error");, as the exception came from a regular page and the response should be HTML.
From your description, it seems that you want to detect where the exception come from, and if the exception come from the API method, you will use the custom exception handler with custom response, otherwise it will show the error message via the Home/Error page.
In this scenario, an alternative to a custom exception handler page is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the path of the request that made the error before returning the response.
For example:
//app.UseExceptionHandler("/Home/Error");
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var exceptionHandlerPathFeature =
context.Features.Get<IExceptionHandlerPathFeature>();
//check if the handler path contains api or not.
if (exceptionHandlerPathFeature.Path.Contains("api"))
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; ;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("<html lang=\"en\"><body>\r\n");
await context.Response.WriteAsync("ERROR From API!<br><br>\r\n");
await context.Response.WriteAsync(
"<a href=\"/\">Home</a><br>\r\n");
await context.Response.WriteAsync("</body></html>\r\n");
}
else
{
context.Response.Redirect("/Home/Error");
}
});
});
The result as below:

More detail information, see Exception handler lambda and Asp .Net Core How to handle error pages in area.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With