给controller加上description
https://github.com/RSuter/NSwag/issues/1803
xml summary
https://github.com/RSuter/NJsonSchema/wiki/XML-Documentation
WebApiToSwaggerGenerator
- Package: NSwag.SwaggerGeneration.WebApi,NSwag.Annotations
- Settings: WebApiToSwaggerGeneratorSettings
- Usage: Code (below)
The WebApiToSwaggerGenerator
class is used to generate a Swagger specification from ASP.NET Web API controllers:
下面这一块的代码的使用,参看Serve the Swagger specification from a Web API action部分的第二节
var settings = new WebApiToSwaggerGeneratorSettings
{
DefaultUrlTemplate = "api/{controller}/{action}/{id}" }; var generator = new WebApiToSwaggerGenerator(settings); var document = await generator.GenerateForControllerAsync<PersonsController>(); var swaggerSpecification = document.ToJson();
The generator internally uses the JsonSchemaGenerator class (NJsonSchema project) to generate the JSON Schemas of the request and response DTO types.
To generate the Swagger specification for Web API controllers in an external .NET assembly, use the WebApiAssemblyToSwaggerGenerator class.
ASP.NET Core
Important: This reflection based generator will eventually be deprecated by the new APi Explorer based generator AspNetCoreToSwaggerGenerator!
When generating a Swagger specification for an ASP.NET Core application, set the IsAspNetCore
setting to true.
Supported ASP.NET Web API attributes
- Controller classes:
RoutePrefixAttribute
on the controller classDescriptionAttribute
on the controller class (used to fill the Swagger 'Summary')
- Action methods:
RouteAttribute
andActionNameAttribute
on the action method, with support for Route constraints (e.g.[Route("users/{id:int}"]
)DescriptionAttribute
on the action method (used as Swagger operation 'Description')- One or more
ProducesResponseTypeAttribute
on the action method - HTTP verb attributes:
AcceptVerbsAttribute
HttpGetAttribute
HttpPostAttribute
HttpPutAttribute
HttpDeleteAttribute
HttpOptionsAttribute
- Action method parameters:
FromBodyAttribute
on the action method parameterModelBinderAttribute
The generator also supports data annotations, check out this page for more information.
Additionally supported attributes
- Package: NSwag.Annotations
SwaggerResponseAttribute(httpAction, type)
Defines the response type of a Web API action method and HTTP action. See Specify the response type of an action.
SwaggerDefaultResponseAttribute()
Adds the default response (HTTP 200/204) based on the return type of the operation method. This can be used in conjunction with the SwaggerResponseAttribute
or another response defining attribute (ProducesResponseTypeAttribute
, etc.). This is needed because if one of these attributes is available, you have to define all responses and the default response is not automatically added. If an HTTP 200/204 response is already defined then the attribute is ignored (useful if the attribute is defined on the controller or the base class).
SwaggerIgnoreAttribute()
Excludes a Web API method from the Swagger specification.
SwaggerOperationAttribute(operationId)
Defines a custom operation ID for a Web API action method.
SwaggerTagsAttribute(tags)
Defines the operation tags. See Specify the operation tags.
SwaggerExtensionDataAttribute()
Adds extension data to the document (when applied to a controller class), an operation or parameter.
- Package: NJsonSchema
NotNullAttribute and CanBeNullAttribute
Can be defined on DTO properties (handled by NJsonSchema), operation parameters and the return type with:
[return: NotNull]
public string GetName()
The default behavior can be changed with the WebApiToSwaggerGeneratorSettings.DefaultReferenceTypeNullHandling
setting (default: Null).
Serve the Swagger specification from a Web API action
You should use the OWIN middlewares to serve a Swagger specifications via HTTP.
You can serve the Swagger specification by running the Swagger generator in a Web API action method:
[RoutePrefix("api/MyWebApi")]
public class MyWebApiController : ApiController { // TODO: Add action methods here private static readonly Lazy<string> _swagger = new Lazy<string>(() => { var settings = new WebApiToSwaggerGeneratorSettings { DefaultUrlTemplate = "api/{controller}/{action}/{id}" }; var generator = new WebApiToSwaggerGenerator(settings); var document = Task.Run(async () => await generator.GenerateForControllerAsync<MyWebApiController>()) .GetAwaiter().GetResult(); return document.ToJson(); }); [SwaggerIgnore] [HttpGet, Route("swagger/docs/v1")] public HttpResponseMessage Swagger() { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(_swagger.Value, Encoding.UTF8, "application/json"); return response; } }
The Swagger specification can now be accessed via the path http://myhost/api/MyWebApi/swagger/docs/v1
.
The following code shows how to implemented a controller which serves the Swagger specification for multiple controllers: (这个更靠谱)
public class SwaggerController : Controller
{
private static readonly Lazy<string> _swagger = new Lazy<string>(() => { var controllers = new[] { typeof(FooController), typeof(BarController) }; var settings = new WebApiToSwaggerGeneratorSettings { DefaultUrlTemplate = "api/{controller}/{action}/{id}" }; var generator = new WebApiToSwaggerGenerator(settings); var document = Task.Run(async () => await generator.GenerateForControllersAsync(controllers)) .GetAwaiter().GetResult(); return document.ToJson(); }); [SwaggerIgnore] [HttpGet, Route("swagger/docs/v1")] public HttpResponseMessage Swagger() { var response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.OK; response.Content = new StringContent(_swagger.Value, Encoding.UTF8, "application/json"); return response; } }