是HttpContext.Current.User在全局asax中不一樣HttpContext.User在一個action方法中嗎?我爲用戶分配了一些角色,但他們似乎迷失了方向。HttpContext.Current.User!= HttpContext.User?
下面的代碼顯示了正在發生的事情。當用戶登錄時,兩個斷言都會被觸發,首先是全局asax,然後是操作方法。但他們給出了不同的結果。
第一本:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// ... omitted some code to check user is authenticated
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
string[] roles = new string[] { "admin", "user" };
HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(identity, roles);
Assert(HttpContext.User.IsInRole("admin"));
}
然後這在我的操作方法:
public ActionResult Index()
{
bool isAdmin = HttpContext.User.IsInRole("admin");
Assert(isAdmin); // this fails, isAdmin is false
// ...
}
我用下面的資源
http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html
我已經擴大了我的答案,包括關於爲什麼發生這種情況的評論,以及插圖,希望有所幫助。試試'Application_OnPostAuthenticateRequest',如果你真的必須使用這個而不是'WebSecurity' –