Core 7 - Api error handling, model state validation + UseExceptionhandler - api

I am currently working on implementing some Apis using swagger/swashbuckle in net core 7 and implementing some error handling, I've gone down the route of using an exception handler. With separate endpoints from dev/prod.
E.g. Startup.cs
if (env.IsDevelopment())
{
...details ommited
app.UseExceptionHandler("/dev-error");
}
else
{
...details ommited
app.UseExceptionHandler("/error");
}
ErrorController.cs
[AllowAnonymous]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : Controller
{
private ILogger _logger;
public ErrorController(ILogger logger)
{
_logger = logger;
}
[Route("dev-error")]
public IAttempt DevError()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = context.Error;
return Attempt.Fail(exception);
}
[Route("error")]
public IAttempt Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = context.Error;
_logger.Log(LogLevel.Error, exception, exception.Message);
switch (exception)
{
case UnauthorizedAccessException:
Response.StatusCode = (int) HttpStatusCode.Unauthorized;
return Attempt.Fail("Unauthorised");
default:
Response.StatusCode = (int) HttpStatusCode.InternalServerError;
return Attempt.Fail("Generic Error");
}
}
}
The idea is that all responses are of IAttempt, so that the FE user can check if its succeeded etc. and whether to handle the result or exception in a user friendly way.
This has been working great up until now when I've been implementing Api's that require the model to be validated. I wanted to amend the IAttempt class to provide modelstate feedback, however I have tried many approaches and cant seem to get modelstate validation flow through the exception handler.
I wanted to implement a custom ValidationException that contains the errors which is then handled in these controllers. But when an exception is thrown in either an IActionFilter or when overriding the InvalidModelStateResponseFactory the exception isn't caught by the exception handler.
Is there a work around? Am I missing something?
Alternatively I could define a InvalidModelStateResponseFactory that returns a similar model(IAttempt), but it would be nice for Failed requests to be handled in one place.
Cheers in advance

I think you can make the InvalidModelStateResponseFactory redirect to the ErrorController, sending the required data to create your response

According to your description, I suggest you could consider using the customer action filter to achieve your requirement.
Inside the custom action filter, we could get the model state's results, then you could throw the exception inside it.
More details, you could refer to below codes:
1.Create the custom action filter:
public class CustomValidationActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
if (!context.ModelState.IsValid)
{
var errorList = context.ModelState.Values
.SelectMany(m => m.Errors)
.Select(m => m.ErrorMessage)
.ToList();
throw new Exception();
}
}
public void OnActionExecuting(ActionExecutingContext context) { }
}
2.Inside the program.cs
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new CustomValidationActionFilter());
});
Then if it thrown the exception, it will go to the controller's error action method, since you set the global exception handler.

I was unnecessarily over complicating things so I have dropped what I attempted to do as in theory responses should be handled accordingly to their response status code rather then the object thats passed in.

Related

in asp.net core, should i still use try-catch if i already have exception filter?

I'm talking about general functions in controller repositories: database stuff and logic.
I presume that a-sync calls to-from other api should always be with try catch in case those fail.
But about all the other stuff, should i still use try-catch or just one exception filter and be done with it??
I'm not sure what the common architecture use in the industry.
thanks
In my preference and experience Yes, even if you have exception filters in ASP.NET Core, you should still use try-catch blocks. While useful, exception filters might not be able to handle every possible error circumstance in your application.
Try-catch blocks let you handle failures that might happen inside the scope of a particular method or block of code as well as more precisely handle exceptions.
Additionally, they let you to capture exceptions and carry out further processing or logging before re-throwing the exception for handling by a higher-level handler, such an exception filter.
It is possible to handle errors globally with the built-in middleware. So you need to create a class
namespace GlobalErrorHandling.Extensions
{
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureExceptionHandler(this IApplicationBuilder app,
ILoggerManager logger)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode
.InternalServerError;
context.Response.ContentType = "application/json";
var contextFeature = context.Features
.Get<IExceptionHandlerFeature>();
if(contextFeature != null)
{
logger.LogError($"Ooops. : {contextFeature.Error}");
await context.Response.WriteAsync(new ErrorDetails()
{
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error."
}.ToString());
}
});
});
}
}
}
and
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
ILoggerManager logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureExceptionHandler(logger);
// ... the other code is omitted for the brevity
}
Read more in this great article.

Unhandled TaskCancelledException when request is aborted by client in ASP.NET Core MVC

ASP.NET Core MVC provides approach to handle situations when request is aborted by the client. Framework passes CancellationToken that can be accessed via HttpContext.RequestAborted property, or can be bound into controller's action.
In terms of .NET, this approach looks pretty clear, consistent and natural. What doesn't look natural and logical to me is that framework, which initializes, populates and 'cancels' this access token doesn't handle appropriate TaskCancelledException.
So, if
I create a new project from the "ASP.NET Core Web API" template,
Add an action with CancellationToken argument, something like this:
[HttpGet("Delay")]
public async Task<IActionResult> GetDelayAsync(CancellationToken cancellationToken)
{
await Task.Delay(30_000, cancellationToken);
return Ok();
}
And then send request via postman and cancel it before completion
Then the application records this error in the log:
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMCHB3SQHQQR", Request id "0HMCHB3SQHQQR:00000002": An unhandled exception was thrown by the application.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
<<>>
My expectation is that exception in this particular case exception is handled and absorbed by asp.net, with no "fail" records in logs.
Error-wise behavior should be the same as with synchronous action:
[HttpGet("Delay")]
public IActionResult GetDelay()
{
Thread.Sleep(30_000);
return Ok();
}
This implementation doesn't record any errors in logs when request is aborted.
Technically exception can be absorbed and hided by exception filter, but this approach looks weird and overcomplicated. At least because this is routine situation, and writing code for any application doesn't make any sense. Also, I want to hide "exception caused by aborted request when client isn't interested in response" and behavior related to other unhandled TaskCancelledException should remain as is...
I'm wondering how and when it's supposed to properly handle and absorb exception when request is aborted by client?
There are number of articles how to access cancellation token, however I was unable to find any explicit statement that answers my question.
From https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation:
If you are waiting on a Task that transitions to the Canceled state, a
System.Threading.Tasks.TaskCanceledException exception (wrapped in an
AggregateException exception) is thrown. Note that this exception
indicates successful cancellation instead of a faulty situation.
Therefore, the task's Exception property returns null.
That's why this block does not throw (there's no task awaited that is tied to a cancellation token):
[HttpGet("Delay")]
public IActionResult GetDelay(CancellationToken cancellationToken)
{
Thread.Sleep(30_000);
return Ok();
}
I stumbled upon the same issue you described in your post. Genuinely speaking, middleware might not be the worst approach. I found good example in Ocelot API gateway on Github.
Pay attention it will return HTTP 499 Client Closed Request afterwards.
You may modify it in way that no logs will be written.
/// <summary>
/// Catches all unhandled exceptions thrown by middleware, logs and returns a 500.
/// </summary>
public class ExceptionHandlerMiddleware : OcelotMiddleware
{
private readonly RequestDelegate _next;
private readonly IRequestScopedDataRepository _repo;
public ExceptionHandlerMiddleware(RequestDelegate next,
IOcelotLoggerFactory loggerFactory,
IRequestScopedDataRepository repo)
: base(loggerFactory.CreateLogger<ExceptionHandlerMiddleware>())
{
_next = next;
_repo = repo;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
httpContext.RequestAborted.ThrowIfCancellationRequested();
var internalConfiguration = httpContext.Items.IInternalConfiguration();
TrySetGlobalRequestId(httpContext, internalConfiguration);
Logger.LogDebug("ocelot pipeline started");
await _next.Invoke(httpContext);
}
catch (OperationCanceledException) when (httpContext.RequestAborted.IsCancellationRequested)
{
Logger.LogDebug("operation canceled");
if (!httpContext.Response.HasStarted)
{
httpContext.Response.StatusCode = 499;
}
}
catch (Exception e)
{
Logger.LogDebug("error calling middleware");
var message = CreateMessage(httpContext, e);
Logger.LogError(message, e);
SetInternalServerErrorOnResponse(httpContext);
}
Logger.LogDebug("ocelot pipeline finished");
}
private void TrySetGlobalRequestId(HttpContext httpContext, IInternalConfiguration configuration)
{
var key = configuration.RequestId;
if (!string.IsNullOrEmpty(key) && httpContext.Request.Headers.TryGetValue(key, out var upstreamRequestIds))
{
httpContext.TraceIdentifier = upstreamRequestIds.First();
}
_repo.Add("RequestId", httpContext.TraceIdentifier);
}
private void SetInternalServerErrorOnResponse(HttpContext httpContext)
{
if (!httpContext.Response.HasStarted)
{
httpContext.Response.StatusCode = 500;
}
}
private string CreateMessage(HttpContext httpContext, Exception e)
{
var message =
$"Exception caught in global error handler, exception message: {e.Message}, exception stack: {e.StackTrace}";
if (e.InnerException != null)
{
message =
$"{message}, inner exception message {e.InnerException.Message}, inner exception stack {e.InnerException.StackTrace}";
}
return $"{message} RequestId: {httpContext.TraceIdentifier}";
}
}
If you use multiple middlewares it should be first on the invocation list (It's .NET 6)
app.UseMiddleware(typeof(ExceptionHandlerMiddleware));
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

How to a I redirect to Custom Error Handler Page

I want a generic error page for all application errors.
I have followed the guidelines to create a custom error handler in ASP.NET core and this catches the errors as expected. However, I cannot see how to redirect to a generic error handling the page. Examples seemed to be focused on Web API, not UI.
I have the following custom error handling code
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
int exceptionId = ExceptionManager.Publish(exception);
return context.Response.WriteAsync(new ErrorViewModel()
{
ExceptionId = exceptionId
}.ToString());
}
The exception details are logged to a database and return an Id. I have a controller action that displays the Id so the users can report it.
How do I redirect to my error view?
In Startup.cs method you need to call ExceptionHandlerMiddleware like below.
app.UseMiddleware(typeof(ExceptionHandlerMiddleware));
create a middleware class and write below code
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate next;
public ExceptionHandlerMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
//Write you logic
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = 500;
if (IsRequestAPI(context))
{
//when request api
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
State = 500,
message = exception.Message
}));
}
else
{
//when request page
context.Response.Redirect("/Home/Errorpage");
}
}
}
Middleware is "waterfalled" down through until either all have been executed, or one stops execution (in the case of our exception handling, we'll be writing ours so it stops the execution. More on that later).
The first things passed to your middleware is a request delegate. This is a delegate that takes the current HttpContext object and executes it. Your middleware saves this off upon creation and uses it in the Invoke() step.
Invoke() is where the work is done. Whatever you want to do to the request/response as part of your middleware is done here. Some other usages for middleware might be to authorize a request based on a header or inject a header into the request or response. For more examples, check out the Middleware documentation.

Custom error code pages with message

I am trying to create a custom error code page that displays a message I pass to it in my .NET Core MVC 1.1 application. I setup custom error code pages support in the Startup.cs class file and then created a simple view in a controller that does public IActionResult Example1 => NotFound("Some custom error message"). I expected this message to be pushed to the controller however this is not the case. Calling NotFound() without any parameters hits the error controller but as soon as I pass a message through, the controller is never used and a simple text message is displayed.
I could have sworn I used to do this in the past with classic .NET MVC but it has been awhile.
How can I have custom error code pages that display the proper error. I also need the ability in a controller to return the standard text or JSON response during the error for cases when I expect a JSON response (API actions and such). I am assuming there is a way to do this with a attribute but I have yet to find a way to do either of these tasks.
What you could do is something similar to how the StatusCodePages middleware works. That middleware allows a pipeline re-execution model, to allow handling status code errors through the normal MVC pipeline. So when you return a non-successful status code from MVC, the middleware detects that and then re-executes the whole pipeline for a status code error route. That way, you are able to fully design status code errors. But as Chris Pratt already mentioned, those status codes are typically limited to just their code. There is not really a way to add additional details to it.
But what we could do is create our own error handling implementation on top of that re-execution model. For that, we create a CustomErrorResponseMiddleware which basically checks for CustomErrorResponseException exceptions and then re-executes the middleware pipeline for our error handler.
// Custom exceptions that can be thrown within the middleware
public class CustomErrorResponseException : Exception
{
public int StatusCode { get; set; }
public CustomErrorResponseException(string message, int statusCode)
: base(message)
{
StatusCode = statusCode;
}
}
public class NotFoundResponseException : CustomErrorResponseException
{
public NotFoundResponseException(string message)
: base(message, 404)
{ }
}
// Custom context feature, to store information from the exception
public interface ICustomErrorResponseFeature
{
int StatusCode { get; set; }
string StatusMessage { get; set; }
}
public class CustomErrorResponseFeature : ICustomErrorResponseFeature
{
public int StatusCode { get; set; }
public string StatusMessage { get; set; }
}
// Middleware implementation
public class CustomErrorResponseMiddleware
{
private readonly RequestDelegate _next;
private readonly string _requestPath;
public CustomErrorResponseMiddleware(RequestDelegate next, string requestPath)
{
_next = next;
_requestPath = requestPath;
}
public async Task Invoke(HttpContext context)
{
try
{
// run the pipeline normally
await _next(context);
}
catch (CustomErrorResponseException ex)
{
// store error information to be retrieved in the custom handler
context.Features.Set<ICustomErrorResponseFeature>(new CustomErrorResponseFeature
{
StatusCode = ex.StatusCode,
StatusMessage = ex.Message,
});
// backup original request data
var originalPath = context.Request.Path;
var originalQueryString = context.Request.QueryString;
// set new request data for re-execution
context.Request.Path = _requestPath;
context.Request.QueryString = QueryString.Empty;
try
{
// re-execute middleware pipeline
await _next(context);
}
finally
{
// restore original request data
context.Request.Path = originalPath;
context.Request.QueryString = originalQueryString;
}
}
}
}
Now, all we need to do is hook that up. So we add the middleware within our Startup.Configure, somewhere near the beginning:
app.UseMiddleware<CustomErrorResponseMiddleware>("/custom-error-response");
The /custom-error-response is the route that we are re-executing when a custom response is being requested. This can be a normal MVC controller action:
[Route("/custom-error-response")]
public IActionResult CustomErrorResponse()
{
var customErrorResponseFeature = HttpContext.Features.Get<ICustomErrorResponseFeature>();
var view = View(customErrorResponseFeature);
view.StatusCode = customErrorResponseFeature.StatusCode;
return view;
}
Since this uses MVC, this also needs a view:
#model ICustomErrorResponseFeature
#{
ViewData["Title"] = "Error";
}
<p>There was an error with your request:</p>
<p>#Model.StatusMessage</p>
And that’s basically all. Now, we can just throw our custom error response exceptions from our MVC actions to trigger this:
// generate a 404
throw new NotFoundResponseException("This item could not be found");
// or completely custom
throw new CustomErrorResponseException("This did not work", 400);
Of course, we could also expand this further, but that should be the basic idea.
If you are already using the StatusCodePages middleware, you might think whether all this custom re-execution is really necessary, when you already have exactly that in the StatusCodePages middleware. And well, it is not. We can also just expand on that directly.
For that, we will just add the context features, which we can set at any point during the normal execution. Then, we just return a status code, and let the StatusCodePages middleware run. Inside its handler, we can then look for our feature and use the information there to expand the status code error page:
// Custom context feature
public interface IStatusCodePagesInfoFeature
{
string StatusMessage { get; set; }
}
public class StatusCodePagesInfoFeature : IStatusCodePagesInfoFeature
{
public string StatusMessage { get; set; }
}
// registration of the StatusCodePages middleware inside Startup.Configure
app.UseStatusCodePagesWithReExecute("/error/{0}");
// and the MVC action for that URL
[Route("/error/{code}")]
public IActionResult StatusCode(int code)
{
var statusCodePagesInfoFeature = HttpContext.Features.Get<IStatusCodePagesInfoFeature>();
return View(model: statusCodePagesInfoFeature?.StatusMessage);
}
Inside of the normal controller actions, we can set that feature before returning a status code:
HttpContext.Features.Set<IStatusCodePagesInfoFeature>(new StatusCodePagesInfoFeature
{
StatusMessage = "This item could not be found"
});
return NotFound();
It is too bad you cannot intercept NotFound, Unauthorized, etc. responses in a middleware class.
Okay, option three! You can totally intercept those responses, just not inside of middleware, since these are MVC results and will not leave the MVC pipeline. So you have to intercept them within the MVC filter pipeline. But we could absolutely run a filter, for example a result filter, that modifies the result.
The problem is that we still need a way to pass the information on. We could use a context feature again, but we can also use the MVC object results. So the idea is that we can just do the following in the MVC actions:
return NotFound("The item was not found");
So usually, that string would be the plain text response. But before the result is being executed and the response is being generated, we can run a result filter to modify this and return a view result instead.
public class StatusCodeResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
// retrieve a typed controller, so we can reuse its data
if (context.Controller is Controller controller)
{
// intercept the NotFoundObjectResult
if (context.Result is NotFoundObjectResult notFoundResult)
{
// set the model, or other view data
controller.ViewData.Model = notFoundResult.Value;
// replace the result by a view result
context.Result = new ViewResult()
{
StatusCode = 404,
ViewName = "Views/Errors/NotFound.cshtml",
ViewData = controller.ViewData,
TempData = controller.TempData,
};
}
// intercept other results here…
}
await next();
}
}
All you need is a view at Views/Errors/NotFound.cshtml now and everything will magically work once you have the filter registered.
You can either register the filter by adding a [TypeFilter(typeof(StatusCodeResultFilter))] attribute to the controller or individual actions, or you can register it globally.
What you want is not possible. When you do something like return NotFound with a message, that message will be included in the response body only if it's left unmolested. When you do something like enable status code pages, the NotFound is simply caught by the middleware, and the request will simply be handed off to your error handling action to ultimately obtain the response. Importantly, that means your original NotFoundResult along with any custom message has been round-filed.

return status code Unauthorized for custom IActionFilter in WebAPI

I am working with asp.net WebAPI and I need to create a custom ActionFilter that does a quick check to see if the user requesting the URI should actually be able to get data back.
They have already been authorized to use the web service via basic auth and their role has been validated via a custom role provider.
The last thing I need to do is to check that they have permission to view the data they are requesting with a parameter in their URI.
Here is my code:
public class AccessActionFilter : FilterAttribute, IActionFilter
{
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> continuation)
{
var result = //code to see if they have permission returns either 0 or 1
if (result==0) {
throw new ArgumentException("You do not have access to this resource");
}
return continuation();
}
}
Currently I just throw an error which is not what I want, I'd rather return System.Net.HttpStatusCode.Unauthorized but I am a little miffed by the method I am overriding and I do not really understand it completely.
How would I go about returning that value?
You are probably best sticking to an exception but using the HttpResponseException which will return an Http status code too.
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
Good question here about this.
p.s.
It may be simpler/cleaner to implement ActionFilterAttribute
public class AccessActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var result = //code to see if they have permission returns either 0 or 1
if (result==0)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
base.OnActionExecuting(actionContext);
}
}
Instead of throwing exception you can set status code
public class ExecutionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var result = 0;//code to see if they have permission returns either 0 or 1
if (result == 0)
{
actionContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("Unauthorized User")
};
}
base.OnActionExecuting(actionContext);
}
}