如何在asp.net mvc5中创建自定义athorization属性?

时间:2016-05-04 07:44:05

标签: c# asp.net-mvc authorization asp.net-mvc-5

我有两个实体集,如下所示:

public class Serial
    {
        [HiddenInput(DisplayValue=false)]
        public int SerialID { get; set; }
        [HiddenInput(DisplayValue=false)]
        public string Id { get; set; }
        [Required(ErrorMessage="Please provide your membership serial")]
        [StringLength(16,ErrorMessage="This field can't be longer as of 16 characters.")]
        public string UserSerial { get; set; }
    }

public class Subscription
    {
        [HiddenInput(DisplayValue=false)]
        public int SubscriptionID { get; set; }
        [Required(ErrorMessage="Please provide a subscription code.")]
        public string AdminSerial { get; set; }
    }

我想创建一个自定义授权属性,以便在我的控制器中设计我的操作方法,具体如下:

  

我想检查Serial中是否有UserSerial的任何值   实体不等于订阅实体中AdminSerial的任何值。   如果上述条件成立,那么应该执行ActionResult方法本身,否则自定义AuthorizeAttribute应该将其重定向到另一个操作方法,这是我尝试过的但它不起作用我错过了什么?

public class RequireSerial : AuthorizeAttribute
    {
        EFDbContext db = new EFDbContext();
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (!db.Subscriptions.Any(s => s.AdminSerial.Equals(db.Serials.Any())))
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Serials", action = "Create" }));
            }
            else
            {
                // Execute the Action method itself
            }
        }
    }

我尝试将此RequireSerial自定义授权属性放在操作方法的顶部,但实际上并没有发生任何事情。

[RequireSerial]
        public ViewResult Checkout()
        {
            return View();
        }

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您需要覆盖OnAuthorization HandleUnauthorizedRequest方法。如果用户未经授权,则HandleUnauthorizedRequest默认执行OnAuthorization方法。 用户登录页面的HandleUnauthorizedRequestredirects的默认实现。

EFDbContext db = new EFDbContext();
public override void OnAuthorization(AuthorizationContext filterContext)
{
    //handle base authorization logic
    base.OnAuthorization(filterContext);     

    //if user is not authorized (by base rules) simply return because redirect was set in 'base.OnAuthorization' call.    
    if (this.AuthorizeCore(filterContext.HttpContext) == false)
    {
       return;
    }

    //Here comes your custom redirect logic:
    if (!db.Subscriptions.Any(s => s.AdminSerial.Equals(db.Serials.Any())))
    {
        filterContext.Result = your redirect url goes here;
    }                  
  }

答案 1 :(得分:-1)

授权基本上是一个“布尔”值(不完全是一个真正的布尔值,但它返回授权或失败) 为了充分理解这一点,MSDN的文章非常明确。

Custom Authorization