2012-09-06 81 views
1

所以我實現了我自己的自定義會員供應商,目前只覆蓋ValidateUser()。我也有signalr工作,目前只是一個簡單的方法,調用發送消息,然後發送給所有聽衆。我想添加一些驗證檢查,以便該命令不能單獨運行。到目前爲止,我已經找到了你可以用這個做:Context.User.Identity.IsAuthenticatedsignalr使用自定義會員供應商

[HubName("messageController")] 
public class MessageController : Hub 
{ 
    public void SendMessage(string message) 
    { 
     if (Context.User.Identity.IsAuthenticated)  // this line not working 
     { 
      Clients.addMessage(message); 
     } 
     else 
     { 
      Clients.addMessage("not authenticated"); 
     } 
    } 
} 

我的問題,但因爲我目前正在使用一個自定義的成員提供值爲false。還有什麼我應該用在這裏呢?

目前,當我登錄我執行:

[AllowAnonymous] 
    [HttpPost] 
    public ActionResult Login(LoginModel model, string returnUrl) 
    { 
     if(Membership.ValidateUser(model.UserName, model.Password)) 
     { 
      // Need something here to actually set the logged in user 
     } 
     return RedirectToAction("Index", ""); 
    } 

缺少什麼我在這裏?我是否需要存儲自己的代碼來處理會話,我嘗試使用FormsAuthentication.SetAuthCookie(model.UserName, true);這有效,但我很確定它的錯誤。當我試圖通過將其更改爲Context.User.IsInRole("Admin")來引入角色時,它返回false。即使我用下面的用戶模型(從未在調試的時候得到這個方法):

public class User : IPrincipal 
{ 
    [Required] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 


    public long UserID; 
    public string Name; 
    public string ConnectionId; 

    public virtual IIdentity Identity 
    { 
     get; 
     set; 
    } 

    public virtual bool IsInRole(string role) 
    { 
     return true; 
    } 

}

我很有信心,我缺這個東西,任何想法?

回答

3

使用FormsAuthentication.SetAuthCookie()確認用戶完全正常後,由MVC3模板創建的默認AccountController確實完全相同。

爲什麼你要Context.User.IsInRole()不能正常工作的原因是因爲不會調用您的自定義User類(框架並不知道這件事),相反,它會嘗試通過RoleProvider得到的角色。您需要構建自定義提供程序並將其與Web.config配合使用,就像您對成員資格提供程序所做的一樣。

+0

謝謝你的工作完美。我在看到評論之前實際執行了此操作,但謝謝。唯一讓你感到困惑的是當你調用Context.User.IsInRole()時,它調用RoleProvider.GetRolesForUser它不會調用RoleProvider.IsUserInRole() – user1434177