注册区域的过滤器

时间:2016-08-19 09:59:54

标签: asp.net-core asp.net-core-mvc

有没有办法为特定区域注册过滤器?

例如下面的代码寄存器全局授权过滤器(强制进行身份验证):

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

我想要这个但仅限于某些领域。

1 个答案:

答案 0 :(得分:2)

您可以编写一个可以动态创建过滤器的自定义IFilterProvider

示例:

public class CustomFilterProvider : IFilterProvider
{
    public int Order
    {
        get
        {
            // This value is fine. The `DefaultFilterProvider` has an order of `-1000` and so is run before this provider.
            return 0;
        }
    }

    public void OnProvidersExecuted(FilterProviderContext context)
    {
    }

    public void OnProvidersExecuting(FilterProviderContext context)
    {
        var controllerActionDescriptor = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
        var controllerType = controllerActionDescriptor.ControllerTypeInfo;

        var areaAttribute = controllerType.GetCustomAttribute<AreaAttribute>();
        if(areaAttribute != null && areaAttribute.RouteValue == "Admin")
        {
            var filter = new TestAuthorizationFilter();
            context.Results.Add(new FilterItem(new FilterDescriptor(filter, FilterScope.Global), filter));
        }
    }
}

在DI中注册提供商:

services.TryAddEnumerable(ServiceDescriptor.Singleton<IFilterProvider, CustomFilterProvider>());