2013-08-26 91 views
2

我想写一个登录方法,认证和授权用户进入我的网站与ASP.NET MVC 4开发。问题是,虽然我在验证后调用FormsAuthentication.SetAuthCookie方法用户在Login方法中并重定向到ViewProfile操作,User.Identity.IsAuthenticated在我的自定义Authorize属性对象中仍然返回false。ASP.NET MVC 4用户认证

我给下面的代码:

[HttpPost] 
[AllowAnonymous] 
public ActionResult Login(LoginModel model) 
{ 
    if (Membership.ValidateUser(model.Username, model.Password)) 
    { 
     FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe); 
     return this.RedirectToAction("ViewProfile"); 
    } 
    ModelState.AddModelError("", "The user name or password provided is incorrect."); 
    return View(model); 
} 

[MyAuthorize(Roles = "Super Role, Seeker")] 
public ActionResult ViewProfile() 
{ 
    if (ModelState.IsValid) 
    { 
    ... 
    } 
} 

这里是MyAuthorizeAttribute类

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] 
public class MyAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContextBase httpContext) 
    { 
     if (httpContext == null) 
      throw new ArgumentNullException("httpContext"); 

     var user = httpContext.User; 
     if (!user.Identity.IsAuthenticated) 
      return false; 

     ... 
    } 
} 

缺少什么我的代码?

+0

你能看到的窗体身份验证cookie在重定向时被设置并在随后的调用中发送? –

回答

4

对于谁可以使用FormsAuthentication,面临类似的情况,要确保在你的web.config文件中存在以下配置的那些

<authentication mode="Forms"></authentication> 

现在一切正常