如何通过链接中的特殊代码提供对控制器的访问

时间:2010-02-17 09:44:37

标签: asp.net-mvc

我有一些控制者只能为管理员角色的用户提供访问权限:

[Authorize(Roles = "Administrators")]

controler即将谈论显示客户的公司详细信息,我想通过某个网址提供对该控制器的访问权限,例如:

  

www.mysite.com/Company/123?code=0932840329809u0932840

生成代码不会有问题,问题是什么是通过该秘密网址提供对控制器的访问的最佳解决方案和只有管理员的秘密URL访问? 日Thnx!

1 个答案:

答案 0 :(得分:1)

您可以通过扩展AuthorizeAttribute来创建自定义属性过滤器。

类似的东西:

public class CustomAuthorizeAttribute : AuthorizeAttribute {

  public string Code { get; set; }

  protected override bool AuthorizeCore(HttpContextBase httpContext) {
    if (base.AuthorizeCore(httpContext)) {
      return true;
    }

    string code = Code ?? GetCode() //parse you code as a parameter or get it from another method
    if (httpContext.Request["code"] == code) {
      return true;
    }

    return false;
  }

}


//I wouldn't recommend parsing the code like this, I would get it in your action filter
[CustomAuthorizeAttribute(Code="0932840329809u0932840")]
public ActionResult Index() {
  return View();
}

查看http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/