私は、ビジネス層サービスの1つを使用して、データベース内の一部のデータを検証してから、リソースを表示する権限をユーザに与える必要があるというカスタムを持っています(AuthorizeAttribute
)。私はサービスの場所「アンチパターン」を使用することを決めた私のAuthorizeAttribute
以内にこのサービスを割り当てることができるようにするために、これはコードです:IAuthorizationFilterをAsp Net Web Apiのサービスロケーションと共に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);
}
}
}
私は自分のアプリケーションでは、このような他の属性のカップルを持っています。おそらく、サービスロケータを使用するのは良い方法ではありません。 Webを少し検索した後に、代わりにIAuthorizationFilter
を使用するように提案している人がいました。しかし、私はこの種の書く方法を知らない。IAuthorizationFilter
。あなたは上記のAuthorizeAttribute
と同じことをするIAuthorizationFilter
と書いてもらえますか?
フィルタでGetGroupByIdAttributeの代わりにAddUserToGroupAttributeを使用しましたか?また、これがDBにヒットした場合、どのようにコードがコンテキストを破棄していますか? – DDiVita
@DDiVita、パッシブアトリビュートの名前を「GetGroupByIdAttribute」としました。私はすでに自分の答えを更新しました。この例では、 '_userGroupService'はビジネス層からのクラスであり、そこにデータアクセス層を呼び出します。したがって、' GetGroupByIdAuthorizationFilter 'にコンテキストを配置する必要はありません。 –