【问题标题】:Share Action with Authorized and Unauthorized User in ASP.NET MVC Controller在 ASP.NET MVC 控制器中与授权和未授权用户共享操作
【发布时间】:2016-01-20 20:29:57
【问题描述】:

我有一个带有控制器的 ASP.NET MVC 应用程序。此控制器中的所有操作都可以由匿名用户访问。但是,如果用户通过了身份验证,我想在操作中做一些特别的事情。目前,我注意到无论如何,在此操作的上下文中,User.Identity.IsAuthenticated 始终为 false。这是我的代码:

public class MyController : Controller
{
  public ActionResult GetProfile(string id)
  {
    if (User.Identity.IsAuthenticated) {
      ViewBag.ShowAuthStuff = true;
    } else {
      ViewBag.ShowAuthStuff = false;
    }
  }
}

如何使经过身份验证的用户和未经身份验证的用户都可以访问相同的操作,但执行不同的操作?我不明白为什么 User.Identify.IsAuthenticated 总是假的。我检查了我的饼干。当我登录时,有一个名为:

.ASPXAUTH

但是,当我访问该操作时,该 cookie 不再可用。

【问题讨论】:

  • 您是使用 Membership Provider 还是自己进行身份验证?

标签: asp.net-mvc authorization


【解决方案1】:

只需同时使用 AuthorizeAllowAnonymous 过滤器:

[Authorize]
[AllowAnonymous]
public ActionResult GetProfile(string id)
{
    if (User.Identity.IsAuthenticated) {
        ViewBag.ShowAuthStuff = true;
    } else {
        ViewBag.ShowAuthStuff = false;
    }
}

虽然匿名访问“个人资料”并没有多大意义。

此外,通常情况下,您不希望在同一个控制器中混合使用授权和未授权的操作。最好将必须或可能需要在一个控制器中授权的操作以及在单独的控制器中进行未经授权的操作。在这种情况下,您可以在控制器本身上指定 Authorize 过滤器,然后在任何想要与经过身份验证的用户交互但不需要它的单个操作上指定 AllowAnonymous

例如在“帐户”控制器中:

[Authorize]
public class AccountsController : Controller
{
    public ActionResult Profile()
    {
        // Login required to reach here
    }

    [AllowAnonymous]
    public ActionResult Login()
    {
        if (User.Identity.IsAuthenticated)
        {
            // Already logged in, redirect to profile
            return RedirectToAction("Profile");
        }

        // Show login form for anonymous user
        return View()
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2012-03-01
    • 1970-01-01
    • 2013-05-18
    • 2011-08-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多