WEBAPI ScopeFilter执行顺序以及OverrideActionFilters

OverrideActionFilters 

当我们在Global设定过滤器时,有些function不希望被卡住,那么就可以在function上面设定OverrideActionFilters ,不执行

 

 

在这之前,我们要知道ScopeFilter的执行顺序

Global=》Controller=》Action

 

如果在action上设定OverrideActionFilters ,那么 Global 和 Controller 将被忽略

 

如果在Controller 上设定OverrideActionFilters ,那么 Global  将被忽略

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebApi.Controllers
{
    internal static class HttpRequestMessageExtensions
    {
        public static IList<IFilter> GetFilters(this HttpRequestMessage requestMessage)
        {
            object filters;
            if (!requestMessage.Properties.TryGetValue("__filters", out filters))
            {
                filters = new List<IFilter>();
                requestMessage.Properties.Add("__filters", filters);
            }
            return (IList<IFilter>)filters;
        }
    }

    [ControllerScopeFilter]
    public class FooController : ApiController
    {
        [ActionScopeFilter]
        public IEnumerable<string> Get()
        {
            return this.Request.GetFilters().Select(filter => filter.GetType().Name);
        }

    }

    [ControllerScopeFilter]
    public class BarController : ApiController
    {
        [ActionScopeFilter]
        [OverrideActionFilters]
        public IEnumerable<string> Get()
        {
            return this.Request.GetFilters().Select(filter => filter.GetType().Name);
        }

    }

    [ControllerScopeFilter]
    public class BazController : ApiController
    {
        public IEnumerable<string> Get()
        {
            return this.Request.GetFilters().Select(filter => filter.GetType().Name);
        }
    }

    [ControllerScopeFilter]
    [OverrideActionFilters]
    public class QuxController : ApiController
    {
        public IEnumerable<string> Get()
        {
            return this.Request.GetFilters().Select(filter => filter.GetType().Name);
        }
    }

    public abstract class FilterBaseAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            actionContext.Request.GetFilters().Add(this);
        }
    }

    public class GlobalScopeFilterAttribute : FilterBaseAttribute { }
    public class ControllerScopeFilterAttribute : FilterBaseAttribute { }
    public class ActionScopeFilterAttribute : FilterBaseAttribute{ }
}

  

posted @ 2021-11-17 17:20  zq爱生活爱代码  阅读(67)  评论(0编辑  收藏  举报