Set one ProducesResponseTypeof for multiple HttpStatusCodes

I am setting ProducesResponseType so that it can be documented with Swagger.

If the response is complete (OK => 200), then it creates an IEnumerable.

[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]

      

But when I get an exception, I catch it and then create an object of my custom APIError class. When I populate an object, I can set different HttpStatusCodes, but in the end I want to set ProducesResponseType to be my APIError class for all other HttpStatusCodes. I mean, I can get BadRequest, ServerInternalError, Forbidden, etc., but they will all have the same response type (ApiError). Is there a way to set this line of code for all HTTP error codes? Or do I need to install it one by one?

[ProducesResponseType(typeof(ApiError), ???)]

      

The end result should look like this:

[ProducesResponseType(typeof(IEnumerable<MyModel>), 200)]
[ProducesResponseType(typeof(ApiError), AllFailureHttpCodes)]

      

+3


source to share


1 answer


I'm afraid this is impossible, at least not for action.

IApiResponseMetadataProvider

(see. here ) has only one property int StatusCode { get; }

, and it is used for both ProducesAttribute

and for ProducesResponseTypeAttribute

.

However, in your special case, you can register it as a global filter though, since the error result should be the same for all actions regardless of whether they are GET, POST, PUT, or DELETE.

services.AddMvc(options =>
{
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 400));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 401));
    options.Filters.Add(new Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute(typeof(ApiError), 409));
});

      

Then they should be applied to every activity in your MVC / WebAPI application.



Word of warning

However , I personally think this is a misnomer, because it would mean that every method you have can handle these types of errors. For example, a 409 specifically for a conflict, in the WebAPI you are using, when there is an error when updating a resource, i.e. when using optimistic concurrency, the record was modified by another user and hence the version of the record was changed and Failed to update.

Adding them to all methods is simply wrong. You should only add a status code if your activity is actually handling that status code. For example, 409 is only suitable for PUT and POST methods. Where 404 might be suitable for GET and PUT (update), but less suitable for POST (inserts).

This is especially bad when you use tools like Swagger to create Api Docs then you just end up with incorrect documentation. You should look at ProducesResponseType

both the form of the documentation and as such, you should not take an overly general approach for this.

+3


source







All Articles