Some api response codes, such as 500 for Internal server error, are the same for all API endpoints.
Let’s see how to implement such general behaviour using Swashbuckle.
Add below classes:
public class InternalServerErrorModel { public string Message { get; set; } public string ExceptionMessage { get; set; } public string ExceptionType { get; set; } public string StackTrace { get; set; } } public class InternalServerErrorResponseFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { var schema = schemaRegistry.GetOrRegister(typeof(InternalServerErrorModel)); if (!operation.responses.ContainsKey("500")) { operation.responses.Add(new KeyValuePair<string, Response>("500", new Response() { description = "Internal server error occured", schema = schema })); } } }
Register new operation filter in SwaggerConfig.cs
c.OperationFilter<InternalServerErrorResponseFilter>();
And after running the application, each endpoint descriptions is decorated with:
Important!
Model above is default for asp.net web api, but it is security issue to expose internal details such Exception stack trace to outside world. Much better is to log exceptions to database using, for example, ELMAH library, and return just Error ID to clients.