2

I gonna use these attributes on my controller:

    [SwaggerResponse((int)HttpStatusCode.OK, typeof(GetAutotopupConfigurationResponse))]
    [SwaggerResponse((int)HttpStatusCode.BadRequest, typeof(ErrorResponse), BadRequestMessage)]
    [SwaggerResponse((int)HttpStatusCode.Unauthorized, typeof(ErrorResponse), InvalidCredentiasMessage)]
    [SwaggerResponse((int)HttpStatusCode.Forbidden, typeof(ErrorResponse), UserNoRightsMessage)]
    [SwaggerResponse((int)HttpStatusCode.NotFound, typeof(ErrorResponse), AutopopupNotFoundMessage)]
    [SwaggerResponse((int)HttpStatusCode.InternalServerError, typeof(ErrorResponse), InternalServerErrorMessage)]

How do I simplify the logic and reduce code ammount or make it more flexible somehow?

Rostyslav Fedyk
  • 307
  • 1
  • 3
  • 10
  • if there is chanse to group them try this https://stackoverflow.com/questions/38503146/combining-multiple-attributes-to-a-single-attribute – irvin Dec 07 '18 at 13:30

1 Answers1

0

EDIT This answer applies to Asp.Net-Core but may be useful for this question too.

If you're using Swashbuckle you can use an IOperationFilter and Reflection to target specific endpoints and programmatically apply the responses.

It's possible to use an IOperationFilter to apply InternalServerError to all endpoints in your service. Below is an example:

public class ServerErrorResponseOperationFilter : IOperationFilter
{            
    // Applies the specified operation. Adds 500 ServerError to Swagger documentation for all endpoints            
    public void Apply(Operation operation, OperationFilterContext context)
    {
        // ensure we are filtering on controllers
        if (context.MethodInfo.DeclaringType.BaseType.BaseType == typeof(ControllerBase)
            || context.MethodInfo.ReflectedType.BaseType == typeof(Controller))
        {
            operation.Responses.Add("500", new Response { Description = "Server Error" });
        }                        
    }
}

You need to set Swagger to use these filters. You can do so by adding in the setup:

services.AddSwaggerGen(swag =>
{
    swag.SwaggerDoc("v1", new Info { Title = "Docs", Version = "v1" });

    // add swagger filters to document default responses
    swag.OperationFilter<ServerErrorResponseOperationFilter>();
});

You can use other filters to apply 401 Unauthorized, 403 Forbidden, etc. You can even use Reflection to add 201 Created for actions decorated with [HttpPost] and you could do something similar for other Http attributes.

If you have filters for 401, 403 and 500 that will tidy up your controller slightly. You will still need to add attributes for certain methods that can't be dealt with by Reflection. With this method I find I only need to add one or 2 attributes, typically [ProcudesResponseType((int)HttpStatusCode.BadRequest)] and [ProcudesResponseType((int)HttpStatusCode.NotFound)].

haldo
  • 14,512
  • 5
  • 46
  • 52