したがって、IAuthorizationFilter を実装する必要があるのか、IActionFilter を実装する必要があるのか 、それとも何か他のものを実装する必要があるのか わかりません。
以下を実装する必要がありますIAuthorizationFilter
。
public class MyAuthorizeAttribute: FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var key = filterContext.HttpContext.Request.QueryString["param_name"];
if (!IsValid(key))
{
// Unauthorized!
filterContext.Result = new HttpUnauthorizedResult();
}
}
private bool IsValid(string key)
{
// You know what to do here => go hit your RavenDb
// and perform the necessary checks
throw new NotImplementedException();
}
}
また、カスタム アクション フィルターに依存性注入を使用する場合はfollowing article
、カスタム フィルター プロバイダーを実装できる を参照してください ( IFilterProvider
)。コントローラー アクションで使用できるマーク付き属性を設定し、このカスタム フィルター プロバイダーで、アクションがこのマーカー属性で装飾されているかどうかを確認し、カスタム承認フィルターを適用することができます。
例えば:
public class MyAuthorizeAttribute: Attribute
{
}
承認フィルターは のみを実装しIAuthorizationFilter
、 にはなりませんFilterAttribute
:
public class MyAuthorizationFilter: IAuthorizationFilter
{
private readonly ISomeRepository repository;
public class MyAuthorizationFilter(ISomeRepository repository)
{
this.repository = repository;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
var key = filterContext.HttpContext.Request.QueryString["param_name"];
if (!IsValid(key))
{
// Unauthorized!
filterContext.Result = new HttpUnauthorizedResult();
}
}
private bool IsValid(string key)
{
// You know what to do here => go hit your RavenDb
// and perform the necessary checks
throw new NotImplementedException();
}
}
そして、カスタム フィルター プロバイダーが作成されます。
public class MyFilterProvider : IFilterProvider
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
if (actionDescriptor.GetCustomAttributes(typeof(MyAuthorizeAttribute), true).Any())
{
var filter = DependencyResolver.Current.GetService<MyAuthorizationFilter>();
yield return new Filter(filter, FilterScope.Global);
}
yield break;
}
}
それはあなたのに登録されますApplication_Start
:
FilterProviders.Providers.Add(new MyFilterProvider());