我有一个习惯AuthorizeAttribute
,在授予用户查看资源的权限之前,我需要使用其中一项业务层服务来验证数据库中的一些数据。为了能够在我的内部分配此服务,AuthorizeAttribute
我决定使用服务位置“反模式”,这是代码:
internal class AuthorizeGetGroupByIdAttribute : AuthorizeAttribute
{
private readonly IUserGroupService _userGroupService;
public AuthorizeGetGroupByIdAttribute()
{
_userGroupService = ServiceLocator.Instance.Resolve<IUserGroupService>();
}
//In this method I'm validating whether the user is a member of a group.
//If they are not they won't get a permission to view the resource, which is decorated with this attribute.
protected override bool IsAuthorized(HttpActionContext actionContext)
{
Dictionary<string, string> parameters = actionContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
int groupId = int.Parse(parameters["groupId"]);
int currentUserId = HttpContext.Current.User.Identity.GetUserId();
return _userGroupService.IsUserInGroup(currentUserId, groupId);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContex)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(actionContex);
}
else
{
actionContex.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}
我的应用程序中有几个其他类似的属性。使用服务定位器可能不是一个好方法。在网上搜索了一下之后,我发现有些人建议改用IAuthorizationFilter
依赖注入。但我不知道如何写这种IAuthorizationFilter
. 你能帮我写出和上面IAuthorizationFilter
一样的东西AuthorizeAttribute
吗?