Using action parameters in custom Authorization Attribute in ASP.NET MVC3

前端 未结 4 1532
时光取名叫无心
时光取名叫无心 2020-12-13 19:42

I have a controller which should only request authorization when loaded with specific parameters. Like when the parameter ID is 8 for example.

I came up with using a

4条回答
  •  一整个雨季
    2020-12-13 20:25

    As long as AuthorizeAttribute is being inherited, you can get your parameter from AuthorizationContext, as follows:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string idParam = filterContext.Controller.ValueProvider.GetValue("id").AttemptedValue;
            int id;
    
            if (int.TryParse(idParam, out id))
            {
                if (id == 8) // apply your business logic here
                    return;
            }
    
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
    
    [MyAuthorize]
    public ActionResult Protected(int id)
    {
        return View();
    }
    

    The ValueProvider will iterate through all registered providers that by default includes RouteDataValueProvider, QueryStringValueProvider and FormValueProvider, and do all the work for you.

    Otherwise I recommend using ActionFilterAttribute.

提交回复
热议问题