C# swagger应用

1、使用Nuget,对WebAPI项目添加swagger-net的引用

SwaggerConfig 配置如下

using System.Web.Http;
using WebActivatorEx;
using MebAPI;
using System; 
using System.Collections.Generic; 
using Swagger.Net.Application;
using Swagger.Net;
using System.Web.Http.Description; 

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace MebAPI
{
    /// <summary>
    /// 
    /// </summary>
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "WebApi接口文档");
                    c.IncludeXmlComments(GetXmlCommentsPath(thisAssembly.GetName().Name));
                    c.UseFullTypeNameInSchemaIds();
                    c.OperationFilter<HttpAuthHeaderFilter>();

                })
                .EnableSwaggerUi(c =>
                {

                });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected static string GetXmlCommentsPath(string name)
        {
            return string.Format(@"{0}in{1}.XML", AppDomain.CurrentDomain.BaseDirectory, name);
        }

        public class HttpAuthHeaderFilter : IOperationFilter
        {
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
            {
                if (operation.parameters == null)
                    operation.parameters = new List<Parameter>();

                operation.parameters.Add(new Parameter { name = "Authorization", @in = "header", description = "授权", required = false, type = "header" });

            }
        }
    }

}

生成输出xml配置

原文地址:https://www.cnblogs.com/su-king/p/12167213.html