![]() ![]() Return new ObjectResult(new ApiResponse(code)) Yield return new ValidationResult("ProductId is invalid", new ")] Public IEnumerable Validate(ValidationContext validationContext) Here is our model: public class GetProductRequest : IValidatableObject Returning the validation information to the client as JSON is one easy line of code. Assuming that we are using model binding, we get validation for free by using data annotations and/or IValidatableObject. ![]() At a minimum, we need to let them know which fields are incorrect and ideally, we would return an informative message for each failure. If a client passes you invalid data, returning a 400 Bad Request is not going to be helpful enough for the client to diagnose the problem. With zero configuration, this is what ASP.NET Core gives us out of the box.ĭepending on your requirements, this may be acceptable for many common status codes but it will rarely be sufficient for validation failures. Simply returning a 404 status code (with no response body) for an API route that does not exist may provide the client with enough information to fix their code. With an API, while not ideal, empty response bodies are far more permissible for many invalid request types. With MVC actions, failure to display a friendly error page is unacceptable in a professional application. Much of the time, it is practically the same flow but instead of returning a View, we return JSON. While we want to return information in a different format for Web API actions, the techniques for handling errors are not so different from MVC. It bloats the response with HTML and makes client code difficult because JSON (or XML) is expected, not HTML. ![]() An error page is not helpful in these situations. Instead we check the status code and parse the response to determine if our action was successful, displaying data to the user as necessary. With an API, this is not generally the case.ĪPI calls are most often called by back-end code or javascript code and in both cases, you never want to simply display the response from the API. MVC actions are typically executed as a result of a user action in the browser so returning an error page to the browser is the correct approach. However, despite the similarities, when it comes to error handling, you almost certainly want to use a different approach for API errors. Net Core, MVC and Web API have been combined so you now have the same controllers for both MVC actions and API actions. Why do we need a different approach from MVC? This post looks at the best ways to handle exceptions, validation and other invalid requests such as 404s in ASP.NET Core Web API projects and how these approaches differ from MVC error handling. Handling errors in an ASP.NET Core Web API ![]()
0 Comments
Leave a Reply. |