plina

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

MVC中经常会用到关于设置访问权限的问题:

如果我们扩展了AuthorizeAttribute,那么我们只需要在类或方法前加上此attribute,即可实现权限问题。

AttributeTargets 权限适用于类或者方法

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,Inherited=true,AllowMultiple=true)]
    public sealed class SecurityAuthorizationAttribute :AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentException("httpContext");
            }
            bool result = true;
        // 权限设置
return result; } //return true 是不会触发 handleUnauthorizedRequest.
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { //base.HandleUnauthorizedRequest(filterContext); filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml", ViewData = new ViewDataDictionary() { { "ErrorMessage", Constants.IsAccessDenied } } }; } }
//没有权限时候跳转到的error页面。

 

posted on 2016-11-10 17:20  plina  阅读(396)  评论(0编辑  收藏  举报