在ASP.NET MVC3中的自定义授权属性中使用操作参数

时间:2011-04-05 08:49:23

标签: asp.net-mvc-3 authorization custom-attributes

我有一个控制器,只应在加载特定参数时请求授权。例如,当参数ID为8时。

我想到了使用这样的自定义验证属性:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (/* Action's inputparameter ID = 8 */)
        {
        return base.AuthorizeCore(httpContext);
        }
        return true;
    }
}

我的动作看起来像这样(不是很有趣)

[MyAuthorize]
public ActionResult Protected(int id)
{
    /* custom logic for setting the viewmodel from the id parameter */
    return View(viewmodel);
}

问题是您可以看到我不知道如何在authorize属性中检查该ID参数。 你能帮我解决一下吗?

4 个答案:

答案 0 :(得分:29)

如果id作为请求参数(GET或POST)或路由数据参数传递:

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;
}

答案 1 :(得分:9)

只要继承AuthorizeAttribute,您就可以从AuthorizationContext获取参数,如下所示:

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();
}

ValueProvider将遍历所有已注册的提供商,默认情况下包括RouteDataValueProviderQueryStringValueProviderFormValueProvider,并为您完成所有工作。

否则我建议使用ActionFilterAttribute

答案 2 :(得分:2)

你需要这样的东西。

    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"];
        }
    }

答案 3 :(得分:1)

    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;
 }