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

谁都会走 提交于 2019-11-28 18:45:49

If the id is passed as request parameter (GET or POST) or as a route data parameter:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    // first look at routedata then at request parameter:
    var id = (httpContext.Request.RequestContext.RouteData.Values["id"] as string) 
             ??
             (httpContext.Request["id"] as string);
    if (id == "8")
    {
        return base.AuthorizeCore(httpContext);
    }
    return true;
}

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.

You need something like this.

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        int? id = GetId(filterContext);

        if (id.HasValue)
        {
          ...
        }
    }

    private static int? GetId(ActionExecutingContext filterContext)
    {
        int? Id = null;

        if (filterContext.ActionParameters.ContainsKey("Id"))
        {
            Id = (int?)filterContext.ActionParameters["Id"];
        }
    }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var rd = httpContext.Request.RequestContext.RouteData;
        string currentAction = rd.GetRequiredString("action");
        string actionparam =Convert.ToString(rd.Values["param"]);

        if (id == actionparam)
        {
            return base.AuthorizeCore(httpContext);
        }
return true;
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!