2013-04-02 178 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() 
    } 
}