简体   繁体   中英

Find API Route Properties from IApplicationModelProvider context in Net Core?

I wrote an API. Trying to auto register the NSwagger documentation.

How do I derive the route into another variable? [Action]/{id} ? For one below, its HttpGet. and contains 'Action/Id' etc,

Needs to be done through IApplicationModelProvider, and similarly through Controller Model and Action Model kind of loop.

*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,

Net Core API: Make ProducesResponseType Global Parameter or Automate

    [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 :)

All you have to do is add a couple of lines to your Startup.cs:

  1. Add NuGet package Swashbuckle.AspNetCore to your REST project.

     dotnet add package Swashbuckle.AspNetCore
  2. Register Swashbuckle in your Startup.cs

     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. Start your app, browse to http://localhost:<port>/swagger , and enjoy your new UI:

NOTE: The syntax above was valid in .Net Core 2.x. It has changed slightly for .Net Core 3.0:

NEW SYNTAX (.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. In Startup.cs > ConfigureServices(), substitute Microsoft.OpenApi.Models.OpenApiInfo for Swagger.Info .

EXAMPLE:

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

You can go to action.Attributes.OfType<HttpMethodAttribute>(). and then in Template, you will notice the Route Value. See image below in Visual Studio Debugging Window.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM