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?