1

大家好,我有两个登录名,但是如何使用 authorize 分配这些登录 URL?

这是我的网络配置:

 <location path="Home">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>  
  </location>


 <authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="2880" />
    </authentication>

那么如何创建第二个 loginurl 呢?

4

1 回答 1

6

表单身份验证中不能有 2 个登录 url。如果您需要实现此功能,您可以编写自定义[Authorize]属性,然后覆盖HandleUnauthorizedRequest方法,您可以在其中重定向到相应的登录 url。

例如:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string _controller;
    private readonly string _action;
    public MyAuthorizeAttribute(): this("account", "logon")
    {
    }

    public MyAuthorizeAttribute(string controller, string action)
    {
        _controller = controller;
        _action = action;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var values = new RouteValueDictionary(new
        {
            controller = _controller,
            action = _action,
            returnurl = filterContext.HttpContext.Request.Url.PathAndQuery
        });
        filterContext.Result = new RedirectToRouteResult(values);
    }
}

进而:

public class SomeController
{
    [MyAuthorize]
    public ActionResult Foo()
    {
        return View();
    }

    [MyAuthorize("account", "someotherlogonaction")]
    public ActionResult Bar()
    {
        return View();
    }
}
于 2012-09-21T07:26:40.847 回答