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)]
.