Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How in error handling action determine should I return web view or api response

In Asp.net Core project I have both web UI and Web API controllers. I followed https://www.devtrends.co.uk/blog/handling-errors-in-asp.net-core-web-api article and included in startup.cs:

app.UseStatusCodePagesWithReExecute("/Error/error/{0}");
app.UseExceptionHandler("/Error/error/500");

And added error handling action in ErrorController:

[Route("error/{code}")]
public IActionResult Error(int code)
{
    return new ObjectResult(new ApiResponse(code));
}

This is good for web api, but not for web pages. For api we want to return custom object (serialised as JSON) , but for UI we want to return custom view. I want to write something like

public IActionResult Error(int code)
{
     if(CalledFromApiClient())
     {
           return new ObjectResult(new ApiResponse(code));
     }
     else
        return View(“Error”);
}

The question is how to implement CalledFromApiClient?

I am thinking to keep all api controllers in api subfolder/namespace and use callstack to find was exception thrown from api controller or not. It should work, but it doesn’t look good.

Is any better way?

            

like image 776
Michael Freidgeim Avatar asked Dec 10 '25 01:12

Michael Freidgeim


1 Answers

I finally found an answer in the blog of the same author https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core

A common example for this requirement is a project with both MVC and API actions where you want to error handling to be different for each.

We assume that url paths follow the convention that api controller actions Start WithSegment "api"

// returns Api error response
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
    appBuilder.UseStatusCodePagesWithReExecute("/apierror/{0}");
appBuilder.UseExceptionHandler("/apierror/500");
});
// returns MVC error page
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
    appBuilder.UseStatusCodePagesWithReExecute("/error/{0}");
appBuilder.UseExceptionHandler("/error/500");
});
like image 110
Michael Freidgeim Avatar answered Dec 12 '25 02:12

Michael Freidgeim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!