问题描述
webapi自定义的一种验证方式(token放入header里),使用swagger测试时由于header里没值所以一直拿不到用户.
解决如下:(从标题2开始,标题1处处理全局验证用户)
1.新建GlobalAuthorizationFilter类
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true),]
public class GlobalAuthorizationFilter: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// 这是一个基本例子,使用的ASP.NET Forms 身份验证
var context = HttpContext.Current;
string methodName1 = actionContext.ActionDescriptor.ActionName;
//var ad=actionContext.ActionDescriptor.MethodInfo;
var session = context.Session;
if(SysConfig.GetCurUser()==null) /*自定义验证方式(从header取token并验证);同样适用于session验证(先登录,然后打开swagger测试)*/
{
PreUnauthorized(actionContext); /*用户验证未通过,则输出 请登录*/
return;
}
}
private void PreUnauthorized(HttpActionContext actionContext)
{
// 如果用户没有登录,则返回一个通用的错误Model
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden,"请登录");
}
}
2.新建GlobalHttpHeaderFilter 类
public class GlobalHttpHeaderFilter : 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 isNeedLogin = apiDescription.ActionDescriptor.GetCustomAttributes<GlobalAuthorizationFilter>().Any(); //是否有验证用户标记
if (isNeedLogin)//如果有验证标记则 多输出2个文本框(swagger form提交时会将这2个值放入header里)
{
operation.parameters.Add(new Parameter { name = "UserUUId", @in = "header", description = "UserUUId", required = false, type = "string" });
operation.parameters.Add(new Parameter { name = "Sign", @in = "header", description = "Sign", required = false, type = "string" });
}
}
}
3.修改app_start文件夹下swaggerconfig.cs文件
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.OperationFilter<Filters.GlobalHttpHeaderFilter>();/*添加此行*/
...
}
4.给需要验证用户的方法打上GlobalAuthorizationFilter标记
[HttpPost]
[Filters.GlobalAuthorizationFilter]
public T_User TestCurLoginUser()
{
return SysConfig.GetCurUser();
}
此时使用swagger测试该方法,会发现如上图所示多了2个输入框
而此时其他没有打GlobalAuthorizationFilter标记的方法则没有这2个输入框
参考:http://www.cnblogs.com/Flyear/p/4875066.html
From:http://www.cnblogs.com/xuejianxiyang/p/6232986.html