2013-04-02 111 views
1

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

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

如何使它使得这两个身份验证和未经验证的用户可以访问相同的动作,但做不同的事情?我无法弄清楚为什么User.Identify.IsAuthenticated始终是false。我检查了我的cookies。当我登录时,有一个名为cookie的:

.ASPXAUTH

然而,当我访问的动作,该cookie不再可用。

+0

您使用的成员资格提供或做你自己的身份验证? –

回答

2

只需使用两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() 
    } 
}