Swagger相关配置记录

Posted huangzelin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swagger相关配置记录相关的知识,希望对你有一定的参考价值。

1、SwaggerConfig文件配置

 public class SwaggerConfig
    {
        protected static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}inxxx.OMS.WebApi.Partner.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }

        protected static string GetCommonXmlCommentsPath()
        {
            return System.String.Format(@"{0}inxxx.OMS.Common.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }

        protected static string GetDtoXmlCommentsPath()
        {
            return System.String.Format(@"{0}inxxx.OMS.Data.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }

        protected static string GetXFCCommentsPath()
        {
            return System.String.Format(@"{0}inxxx.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }

        private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
        {
            //过滤由多版本的controller带来的重复route注册api desc,按命名空间的版本信息过滤,只返回版本内的api
            return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerType.FullName.ToLower().Contains(string.Format(".{0}.", targetApiVersion));
        }

        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "xxx.OMS.WebApi.Partner");
                    c.SchemaId(x => x.FullName);  //避免类型命名冲突
                    c.IncludeXmlComments(GetCommonXmlCommentsPath());
                    c.IncludeXmlComments(GetXmlCommentsPath());
                    c.IncludeXmlComments(GetDtoXmlCommentsPath());
                    c.IncludeXmlComments(GetXFCCommentsPath());
                    c.OperationFilter<HttpHeaderFilter>();
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                })
                .EnableSwaggerUi(c =>
                {
                    c.DisableValidator();
                });
        }
    }

2、HttpHeaderFilter 请求头参数设置

public class HttpHeaderFilter : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation.parameters == null) operation.parameters = new List<Parameter>();
            var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
            //判断是否添加权限过滤器
            var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter);
            //判断是否允许匿名方法
            var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
            if (isAuthorized && !allowAnonymous)
            {
                operation.parameters.Add(new Parameter
                {
                    name = "appId",
                    @in = "header",
                    description = "应用Id",
                    required = true,
                    type = "string"
                });

                operation.parameters.Add(new Parameter
                {
                    name = "accessToken",
                    @in = "header",
                    description = "接口访问token",
                    required = true,
                    type = "string"
                });
            }
        }
    }

3、AccessTokenAttribute身份认证

 public class AccessTokenAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 获取认证服务
        /// </summary>
        /// <returns></returns>
        private IOpenAuthService GetAuthService()
        {
            return xxx.OMS.Service.Common.ServiceMediatorManager.OpenAuthService;
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var request = actionContext.Request;
            if (request.Headers.Contains("appId") 
                && request.Headers.Contains("accessToken"))
            {
                var appId = request.Headers.GetValues("appId").SingleOrDefault();
                var accessToken = request.Headers.GetValues("accessToken").SingleOrDefault();

                var authRequest = new AuthRequest()
                {
                    AppId = appId,
                    AccessToken = accessToken
                };

                var checkResult = GetAuthService().Check(authRequest);
                if (!checkResult.isOk || !checkResult.retBody)
                {
                    return false;
                }

                var accountResult = GetAuthService().GetAccount(authRequest);
                if (!accountResult.isOk || accountResult.retBody == null)
                {
                    return false;
                }

                var account = accountResult.retBody;
                var customer = new CustomerInfo
                {
                    AppId = account.AppId,
                    SupplierId = account.SupplierId,
                    SupplierName = account.SupplierName
                };

                HttpContext.Current.User = new CustomerPrincipal(new CustomerIdentity(customer));
                return true;
            }
            return false;
        }

        /// <summary>
        /// 处理未授权的请求
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            var content = JsonConvert.SerializeObject(new ResultObject() { retStatus = 401, retMsg = "appId或者accessToken无效" });
            actionContext.Response = new HttpResponseMessage
            {
                Content = new StringContent(content, Encoding.UTF8, "application/json"),
                StatusCode = HttpStatusCode.OK
            };
        }
    }

4、JsonDateTimeConverter Json日期转换

/// <summary>  
    /// Json日期带T格式转换  
    /// </summary>  
    public class JsonDateTimeConverter : IsoDateTimeConverter
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime dataTime;
            if (DateTime.TryParse(reader.Value.ToString(), out dataTime))
            {
                return dataTime;
            }
            else
            {
                return existingValue;
            }
        }

        /// <summary>
        /// 格式化
        /// </summary>
        public JsonDateTimeConverter()
        {
            DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        }
    }  

 

以上是关于Swagger相关配置记录的主要内容,如果未能解决你的问题,请参考以下文章

Spring 4.2.2以上版本和swagger集成方案和踩过的坑

Swagger2相关配置和使用

从零开始配置vim(27)——代码片段

Swagger docs - 单个 http 响应的多个错误代码

从零开始配置vim(27)——代码片段

从零开始配置vim(27)——代码片段