如何将传入的模型传递给属性

时间:2015-08-23 15:33:51

标签: c# asp.net backend

所以我想授权用户使用特定项目。例如:

      [Authorize(Roles = ItemAccess.AuthorizedRoleList(AccessType.Write,id))]
      public ActionResult Edit(Guid id)
      {
      }

但我无法访问id属性。谁能告诉我如何正确实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以编写自定义授权属性,您可以访问id参数并执行任何必要的逻辑:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authenticated
            return false;
        }

        var rd = httpContext.Request.RequestContext.RouteData;
        string id = rd.Values["id"] as string;
        if (string.IsNullOrEmpty(id))
        {
            // No id was specified => we do not allow access
            return false;
        }

        string roles = ItemAccess.AuthorizedRoleList(AccessType.Write, id);
        return httpContext.User.IsInRole(roles))
    }
}

最后用这个自定义属性装饰你的控制器动作:

  [MyAuthorize]
  public ActionResult Edit(Guid id)
  {
  }