MVC---Filters

<strong>一、Filters</strong>
1.Authentication: 认证过滤器,在任何其它filters或者action之前运行,但是可以在authorization过滤器之后再次运行。
2.Authorization:授权过滤器,第二个运行,在认证过滤器之后,其它action之前。
3.Action:在action执行或之后运行。
4.Result:在结果被执行前或之后运行。
5.Exception:仅在Filters、Action或Result异常时运行。

<strong>二、使用Authorization Filters</strong>
授权Filters确保只有被允许的用户才可以执行Action。
推荐创建一个AuthorizeAttribute类的子类:

    public class CustomAuthAttribute : AuthorizeAttribute
    {
        private bool localAllowed;
        public CustomAuthAttribute(bool allowedParam)
        {
            localAllowed = allowedParam;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Request.IsLocal)
            {
                return localAllowed;
            }
            else
            {
                return true;
            }
        }
    }

该授权Filter阻止本地请求的访问。

使用自定义的授权Filter:

    public class HomeController : Controller
    {
        // GET: Home
        [CustomAuth(false)]
        public string Index()
        {
            return "This is the Index action on the Home controller";
        }
    }

大多数情况下,会使用内置的授权Filters:

AuthorizeAttribute属性
    public class HomeController : Controller
    {
        // GET: Home
        [Authorize(Users = "admin")]
        public string Index()
        {
            return "This is the Index action on the Home controller";
        }
    }

<strong>三、使用Authentication Filters</strong>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容