Filter
对请求进行过滤。例如,在进行身份验证的基础上增加一些权限判断,对于身份验证通过的用户,检测其是否有开通UserSpace,如果没有则在Response中说明。示例代码如下:
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
private bool _isBaseAuthorized = false;
protected UserSpace UserSpace { get; set; }
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (UserSpace == null)
UserSpace = await GetUserSpaceFromDb(actionContext);
await base.OnAuthorizationAsync(actionContext, cancellationToken);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (!base.IsAuthorized(actionContext))
{
_isBaseAuthorized = false;
return false;
}
else
{
_isBaseAuthorized = true;
if (UserSpace == null) return false;
return true;
}
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!_isBaseAuthorized)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new JsonContent("您的身份验证未通过!")
};
}
else
{
if (UserSpace == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new JsonContent("您没有开通用户空间!")
};
}
}
}
}
测试的时候,会发现无论是哪个用户登录,都只会使用第一个用户的UserSpace实例,好像ApiAuthorizeAttribute
被缓存了一样。其实是因为Asp.net提供这个实例的时候进行了缓存,所以每次请求都是拿到相同的实例,也就是第一个请求时实例化的对象。这个问题也很好解决:只要在OnAuthorizationAsync
的结束的时候把UserSpace
对象重置为null
就好了,同时把UserSpace
传递到当前请求中保存起来。
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
const string KEY_USER_SPACE = "KEY_USER_SPACE";
private bool _isBaseAuthorized = false;
protected UserSpace UserSpace { get; set; }
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (UserSpace == null)
UserSpace = await GetUserSpaceFromDb(actionContext);
actionContext.ControllerContext.Request.Properties.Add(KEY_USER_SPACE, UserSpace);
UserSpace = null; //Because this instance will be reused next time.
await base.OnAuthorizationAsync(actionContext, cancellationToken);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (!base.IsAuthorized(actionContext))
{
_isBaseAuthorized = false;
return false;
}
else
{
_isBaseAuthorized = true;
if (UserSpace == null) return false;
return true;
}
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (!_isBaseAuthorized)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new JsonContent("您的身份验证未通过!")
};
}
else
{
var userSpace = actionContext.ControllerContext.Request.Properties[KEY_USER_SPACE] as UserSpace;
if (userSpace == null)
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new JsonContent("您没有开通用户空间!")
};
}
}
}
}