NSwag给api加上说明
给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;
}
}
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-02-28 Import Example Dataset
2017-02-28 Introduction to MongoDB
2017-02-28 Getting Started with MongoDB (C# Edition)
2017-02-28 本地搭建MongoDB Server