我有兩個控制器,AdminController和的AccountController用下面的代碼ASP.NET MVC 3 HttpContext.Current.User.Identity.IsAuthenticated永遠是假的
的AccountController:
[HttpPost]
public ActionResult LogOn(LogOnViewModel model)
{
if (ModelState.IsValid)
{
_authenticationService.SetPrincipal(model.UserName);
var exists = _authenticationService.ValidateCredentials(userName, password);
FormsAuthentication.SetAuthCookie(model.UserName, false);
if(exists){
return RedirectToAction("Index", "Admin");
}
}
return RedirectToAction("LogOn");
}
AdminController:
[Authenticate]
public class AdminController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
AuthenticateAttribute
繼承自AuthorizeAttribute
並具有以下代碼:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authenticated = false;
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
//some actions
}
else
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
return authenticated;
}
_authenticationService
是AuthenticationService
類的實例和SetPrincipal()
方法有以下代碼:
public void SetPrincipal(string userName)
{
var identity = new GenericIdentity(userName);
var principal = new GenericPrincipal(identity, null);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
var ticket = new FormsAuthenticationTicket(1,
principal.Identity.Name,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
var authenticationCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
if (authenticationCookie != null)
{
authenticationCookie.Value = encryptedCookie;
authenticationCookie.Expires = DateTime.Now.AddMinutes(30);
}
HttpContext.Current.User = principal;
}
}
當我調試,看AuthenticationService.SetPrincipal() HttpContext.Current.User.Identity.IsAuthenticated
是真實的。但重定向到中的AdminController的Index操作總是爲false。結果我再次重定向到LogOn視圖。 我在做什麼錯?
我不爲什麼你使用'HttpContext.Current'當你接收當前HTTP上下文關係中'AuthorizeCore(HttpContextBase的HttpContext)'參數認爲它解決您的問題,但。 –
在httpContext參數中IsAuthenticated屬性也是錯誤的,不幸的是。我無法理解發生了什麼魔術 – anykey3