1、SwaggerConfig文件配置

 public class SwaggerConfig
{
protected static string GetXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\xxx.OMS.WebApi.Partner.XML", System.AppDomain.CurrentDomain.BaseDirectory);
} protected static string GetCommonXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\xxx.OMS.Common.XML", System.AppDomain.CurrentDomain.BaseDirectory);
} protected static string GetDtoXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\xxx.OMS.Data.XML", System.AppDomain.CurrentDomain.BaseDirectory);
} protected static string GetXFCCommentsPath()
{
return System.String.Format(@"{0}\bin\xxx.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 = , 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相关配置记录的更多相关文章

  1. Vue-cli 多页相关配置记录

    Vue-cli 多页相关配置记录 搭建一个顺手的MPA项目脚手架,其实根据项目的不同目录结构和打包配置都可以进行灵活的调整.这次的项目可能是包含各种客户端和管理后台在一起的综合项目所以需要将样式和脚本 ...

  2. nginx的相关配置记录和总结

    前言 本文旨在对nginx的各项配置文件和参数做一个记录和总结. 原因是在配置框架和虚拟目录,web语言解析的nginx环境的时候遇到各种问题和参数,有时百度可以解决,有时直接复制粘贴,大都当时有些记 ...

  3. 个人网站搭建时linux中的相关配置记录(mysql,jdk,nginx,redis)

    一.开发计划(包括准备工作,网站大致需求等) 二.服务器(linux/centos)购买.相应环境配置(jdk),软件安装(mysql, nginx, redis).域名解析 三.原型图.代码开发(v ...

  4. Centos6.4 相关配置记录

    1.手动开启eth0网卡 在虚拟机里装完CentOS6.4之后,使用NAT模式,输入ifconfig发现没有IP地址,查找了一下资料,原来是: 在CentOS 6.x的版本中,默认网卡是不开启的,需要 ...

  5. mac 10.11.6 自带apache配置记录

    详细记录使用自带apache的一些问题 开启apache服务 作为2016年的新版本os,在系统偏好设置里没有网络共享了,所以可以通过终端,直接开启apache服务器: 开启apache:sudo a ...

  6. ios开发之Info.plist文件相关配置

    前言:在iOS开发中有些情况下需要对Info.plist文件进行配置,以下介绍几种相关配置.以后遇到需要配置的再更新... 开发环境:swift3.0.1,Xcode8.1 一,项目中需要使用第三方字 ...

  7. sublime text配置记录

    代码编辑器有一直都有在尝试新的,如brackets/vs code/webstrom,最后还是用回sublime,每次要重新安装的时候都需要上网搜索相关配置资料,特些记录,以备下次使用: 下载地址 下 ...

  8. Linux系统下ssh的相关配置详细解析

    Linux系统下ssh的相关配置进行了详细的分析介绍. ssh是大家常用的登录linux服务器的方式,但是为了安全考虑,有时候我们需要针对ssh做一些特殊处理,本文记录笔者曾经做过的一些修改,供大家参 ...

  9. 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

    不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...

随机推荐

  1. spring boot 接口用例测试

    接口: 测试用例:

  2. 开源项目初涉(C++自我学习开始)

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://i.cnblogs.com/EditPosts.aspx?postid=8428885 临近2018农历新年,我还在上班,哈哈. ...

  3. js 模拟css3 动画1

    <html> <head> <title> javaScript缓动入门 </title> </head> <body> < ...

  4. 转: rem与px的转换

    rem是相对于根元素<html>,这样就意味着,我们只需要在根元素确定一个参考值,这个参考值设置为多少,完全可以根据您自己的需求来定.· 我们知道,浏览器默认的字号16px,来看一些px单 ...

  5. Linux下安装Anaconda

    Anaconda官方下载地址: https://www.anaconda.com/download/ >>bash xxxxxx.sh >>reboot >>sud ...

  6. 恢复mysql 中root 用户的所有权限

    今天在研究数据库的时候不小心吧root用户的权限全给关了.这就尴尬了. 找了半天的解决方案. 如果你的用grant all 无法设定某个用户的权限可以试试这个方法. 1停止mysql服务器.使用ski ...

  7. ubuntu安装gitlab-ci-runner、注册

    首先信任 GitLab 的 GPG 公钥: curl https://packages.gitlab.com/gpg.key 2> /dev/null | sudo apt-key add - ...

  8. cdnbest区域自定义配置里添加防xss攻击配置

    把下面代码复制进去即可: <!--#start 300 --><config> <response action='allow' > <table name= ...

  9. linux网络日志分析

    1.清空日志的技巧 2.访问日志格式分析 3. web日志统计举例

  10. 利用CCS3渐变实现条纹背景

    本文摘自<CSS揭秘>中国工信出版集团 难题: 不论是在网页设计中,还是在其他传统媒介中(比如杂志和墙纸等),各种尺寸.颜色.角度的条纹图案在视觉设计中无处不在.要想在网页中实现条纹图案, ...