[英]Find API Route Properties from IApplicationModelProvider context in Net Core?
I wrote an API.我写了一个 API。 Trying to auto register the NSwagger documentation.
尝试自动注册 NSwagger 文档。
How do I derive the route into another variable?如何将路线导出到另一个变量中? [Action]/{id} ?
[动作]/{id} ? For one below, its HttpGet.
对于下面的一个,它的 HttpGet。 and contains 'Action/Id' etc,
并包含“动作/ID”等,
Needs to be done through IApplicationModelProvider, and similarly through Controller Model and Action Model kind of loop.需要通过 IApplicationModelProvider 来完成,类似地通过控制器模型和动作模型这种循环。
*From knowing the Verb and the Route above, we can register the appropriate StatusCode. *通过了解上面的动词和路由,我们可以注册适当的状态码。 Example: Will require 200 and 500 for All Apis, 404 for Only Get/Id Apis, 400 for Put Apis etc,
示例:所有 API 需要 200 和 500,仅获取/识别 API 需要 404,Put API 需要 400,等等,
Net Core API: Make ProducesResponseType Global Parameter or Automate Net Core API:使 ProducesResponseType 全局参数或自动化
[HttpGet("[Action]/{id}")]
public async Task<ActionResult<GetDepartmentResponse>> GetByDepartment(int id)
{
try
{
var department = await departmentAppService.GetDepartmentById(id);
var response = new GetDepartmentResponse { Body = department };
return Ok(response);
}
Need to know by reading the following similar loop below,需要通过阅读下面的类似循环来了解,
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
foreach (ControllerModel controller in context.Result.Controllers)
{
foreach (ActionModel action in controller.Actions)
{
try
{
if (action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments().Any())
{
Type returnType = action.ActionMethod.ReturnType.GenericTypeArguments[0].GetGenericArguments()[0];
var methodVerbs = action.Attributes.OfType<HttpMethodAttribute>().SelectMany(x => x.HttpMethods).Distinct();
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status200OK));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status500InternalServerError));
}
if (methodVerbs.Contains("GET")) // and contains Route/Id
{
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status404NotFound));
}
if (methodVerbs.Contains("PUT"))
{
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status404NotFound));
}
if (methodVerbs.Contains("POST"))
{
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status201Created));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status400BadRequest));
action.Filters.Add(new ProducesResponseTypeAttribute(returnType, StatusCodes.Status404NotFound));
}
}
catch { }
}
}
}
The Good News is that Swagger will auto-generate everything you need :)好消息是 Swagger 将自动生成您需要的一切:)
All you have to do is add a couple of lines to your Startup.cs:您所要做的就是在 Startup.cs 中添加几行:
Add NuGet package Swashbuckle.AspNetCore to your REST project.将 NuGet 包 Swashbuckle.AspNetCore 添加到您的 REST 项目。
dotnet add package Swashbuckle.AspNetCore
Register Swashbuckle in your Startup.cs在 Startup.cs 中注册 Swashbuckle
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); services.AddMvc(); ... public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(); app.UseStaticFiles(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
Start your app, browse to http://localhost:<port>/swagger
, and enjoy your new UI:启动您的应用程序,浏览到
http://localhost:<port>/swagger
,并享受您的新 UI:
NOTE: The syntax above was valid in .Net Core 2.x.注意:上述语法在 .Net Core 2.x 中有效。 It has changed slightly for .Net Core 3.0:
对于 .Net Core 3.0,它略有变化:
NEW SYNTAX (.Net Core 3.x)新语法(.Net Core 3.x)
1. Nuget > Install Swashbuckle.AspNetCore v5.0.0-rc4
1.
Nuget > Install Swashbuckle.AspNetCore v5.0.0-rc4
<= NOTE: You must check `Include prerelease= Y` in order to see this version
Microsoft.OpenApi.Models.OpenApiInfo
for Swagger.Info
.Microsoft.OpenApi.Models.OpenApiInfo
替换Swagger.Info
。 EXAMPLE:例子:
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1",
new Microsoft.OpenApi.Models.OpenApiInfo {
Title = "Contacts App", Version = "v1"
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.