.Net Core Add Swagger support

 

 

 

1. NuGet added Swashbuckle.AspNetCore

 

 

2. Add Startup Information

Swagger generator to add service set Startup.ConfigureServices method in which:

//注册Swagger生成器,定义一个和多个Swagger 文档
services.AddSwaggerGen(c =>
{
     c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); });

In the  Startup.Configure method, enable middleware provides services for the generation of JSON documents and Swagger UI:

//启用中间件服务生成Swagger作为JSON终结点
app.UseSwagger();
//启用中间件服务对swagger-ui,指定Swagger JSON终结点
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });

 

 

3. Debug default page

 

 

 

4.xml comment information 1591 Comments are ignored warnings, xml in the bin directory, xml same name and project name.

 

 

 

 

 

 

 

5. Add the specific parameters, (query header body path formData) each message can be equipped and powerful.

 

 New class for configuration class IOperationFilter

    public class SwaggerHeaderOperation : IOperationFilter
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null) operation.Parameters = new List<IParameter>();
            var attrs = context.ApiDescription.ActionDescriptor.AttributeRouteInfo;

            //先判断是否是匿名访问,
            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                descriptor.MethodInfo.GetCustomAttributes actionAttributes = var (the inherit: to true);
                BOOL isAnonymous = actionAttributes.Any (A => IS A AllowAnonymousAttribute);
                // non-anonymous way link accesstoken added value
                IF (! isAnonymous)
                {
                    operation.Parameters .add (new new NonBodyParameter ()
                    {
                        the Name = "accessToken",
                        the In = "header", // Query header body path formData
                        the Type = "String",
                        the Required = Are Required to false //
                    });
                }
            }
        }
 
    }

  In IServiceCollection.OperationFilter added <SwaggerHeaderOperation> ();

 

Startup final configuration:

 

        void ConfigureServices public (IServiceCollection Services)
        {
           
            services.AddMvc () SetCompatibilityVersion (CompatibilityVersion.Version_2_1);.
            // Global Json serialization process
            services.AddMvc ()
                .AddJsonOptions (Options =>
                {
                    // Ignore circular reference
                    options.SerializerSettings. = ReferenceLoopHandling.Ignore ReferenceLoopHandling;
                    // do not use hump style Key
                    //options.SerializerSettings.ContractResolver new new LowercaseContractResolver = ();
                    // set the time format
                    options.SerializerSettings.DateFormatString = "the MM-dd-YYYY";
                }
           );

            Services.AddSwaggerGen (C =>
            {// set to Swagger JSON and UI xml document annotation path
                var basePath = Path.GetDirectoryName (typeof (Program ) .Assembly.Location); // Get the application directory (absolute, not by working directory, we suggest using this method to obtain path)
                var XMLPath = Path.Combine (the basePath, "AsnycCoreAPI.xml");
                c.IncludeXmlComments (XMLPath);
                c.SwaggerDoc ( "V1", the Title = {new new Info "My the API ", Version =" V1 "});
                c.OperationFilter <SwaggerHeaderOperation> ();
            });



        }

 

 

        . This Method // Called by the gets the Use The Runtime the this Method to the HTTP Request The Configure Pipeline.
        Public void the Configure (App IApplicationBuilder, IHostingEnvironment the env)
        {
            IF (env.IsDevelopment ())
            {
                app.UseDeveloperExceptionPage ();
            }
            the else
            {
                App .UseHsts ();
            }
            app.UseHttpsRedirection ();
            app.UseMvc ();


            // enable middleware services Swagger generated as JSON endpoint
            app.UseSwagger ();
            // enable middleware service swagger-ui, designated Swagger JSON endpoint
            app.UseSwaggerUI (C =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

        }

 

 

Finally, I wish you all a happy National Day.

 

Guess you like

Origin www.cnblogs.com/j2ee-web-01/p/11599635.html
Recommended