Error handling in the Web API is seen as a cross-cutting issue and should be placed somewhere else in the pipeline, so developers do not need to focus on cross-cutting issues.
You should read Exception Handling in ASP.NET Web Interface
What happens if the web API controller throws an uncaught exception? From default, most exceptions are translated into the HTTP response using status code 500, Internal server error.
as well as global error handling in ASP.NET Web API 2
You should try to keep your controller as long as possible. Error handling, like the source code, will only lead to duplication of code and unnecessary problems for developers. Developers should focus on the core issue, not cross-cutting issues. Just focusing on the main problem, the code above will look like this:
[MyAuthentication] [MyValidateModel] public Vb.Order PostOrderItem(Vb.Order order) { return Vb.Document.Generate(order); }
Why so scarce?
Because:
if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage); }
can be moved to Authentication Filters in ASP.NET Web API 2 which can be applied locally on the controller / action or globally to return an appropriate response.
Testing the model in the ASP.NET web interface as shown
if (!ModelState.IsValid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage); }
You can also move to the filter, for example :.
public class MyValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, actionContext.ModelState); } } }
Nkosi
source share