Share Action with Authorized and Unauthorized User in ASP.NET MVC Controller

核能气质少年 提交于 2019-12-24 18:05:39

问题


I have an ASP.NET MVC app that with a controller. All of the actions in this controller can be accessed by anonymous users. However, if the user is authenticated, I want to do something special in the action. Currently, I've noticed that no matter what, User.Identity.IsAuthenticated is always false in the context of this action. Here is my code:

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

How do I make it such that both an authenticated and an unauthenticated user can access the same action, but do different things? I can't figure out why User.Identify.IsAuthenticated is always false. I checked my cookies. When I'm logged in, there is a cookie named:

.ASPXAUTH

However, when I visit the action, that cookie is no longer available.


回答1:


Just use both Authorize and AllowAnonymous filters:

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

Though it doesn't make a whole lot of sense to have anonymous access to a "profile".

Also, typically, you don't want to mix authorized and unauthorized actions in the same controller. It's better to have actions that must or may require authorization in a controller together, and unauthorized actions in a separate controller. In that case, you specify the Authorize filter on the controller itself, and then AllowAnonymous on any individual actions that want to interact with authenticated users, but don't require it.

For example in an "Accounts" controller:

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


来源:https://stackoverflow.com/questions/15770413/share-action-with-authorized-and-unauthorized-user-in-asp-net-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!