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}\bin\{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配置

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM