簡體   English   中英

從 Net Core 的 IApplicationModelProvider 上下文中查找 API 路由屬性?

[英]Find API Route Properties from IApplicationModelProvider context in Net Core?

我寫了一個 API。 嘗試自動注冊 NSwagger 文檔。

如何將路線導出到另一個變量中? [動作]/{id} ? 對於下面的一個,它的 HttpGet。 並包含“動作/ID”等,

需要通過 IApplicationModelProvider 來完成,類似地通過控制器模型和動作模型這種循環。

*通過了解上面的動詞和路由,我們可以注冊適當的狀態碼。 示例:所有 API 需要 200 和 500,僅獲取/識別 API 需要 404,Put API 需要 400,等等,

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);
        }

需要通過閱讀下面的類似循環來了解,

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 { }
        }
    }
}

好消息是 Swagger 將自動生成您需要的一切:)

您所要做的就是在 Startup.cs 中添加幾行:

  1. 將 NuGet 包 Swashbuckle.AspNetCore 添加到您的 REST 項目。

     dotnet add package Swashbuckle.AspNetCore
  2. 在 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"); });
  3. 啟動您的應用程序,瀏覽到http://localhost:<port>/swagger ,並享受您的新 UI:

注意:上述語法在 .Net Core 2.x 中有效。 對於 .Net Core 3.0,它略有變化:

新語法(.Net Core 3.x)

1. Nuget > Install Swashbuckle.AspNetCore v5.0.0-rc4

<= NOTE: You must check `Include prerelease= Y` in order to see this version
  1. 在 Startup.cs > ConfigureServices() 中,用Microsoft.OpenApi.Models.OpenApiInfo替換Swagger.Info

例子:

  services.AddSwaggerGen(c => {
     c.SwaggerDoc("v1", 
        new Microsoft.OpenApi.Models.OpenApiInfo {
           Title = "Contacts App", Version = "v1" 
     });
  });

你可以去action.Attributes.OfType<HttpMethodAttribute>(). 然后在模板中,您會注意到路由值。 在 Visual Studio 調試窗口中查看下圖。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM