2014-03-05 20 views
0

獲取LoginUserId我已經使用這個方法在mvc5

using Microsoft.AspNet.Identity; 
    var currentUser = User.Identity.GetUserId(); 

但我正在逐漸Error Object reference not set to an instance of an object

而且我也沒能得到網絡的安全性和登錄用戶ID爲mvc4

+0

是'.GetUserId()'一自定義方法?我沒有它,所以錯誤應該位於那裏 – Marco

+0

@Serv使用Microsoft.AspNet.Identity; –

回答

1

使用代碼類似下面,它可以幫助你

public ImportFormFromExcelController() 
     : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) 
    { 
    } 

    public ImportFormFromExcelController(UserManager<ApplicationUser> userManager) 
    { 
     UserManager = userManager; 
    } 

    public UserManager<ApplicationUser> UserManager { get; private set; } 

    public Guid getLoginUserInfoId() 
    { 
     Guid loginUserInfoId = new Guid(); 
     string loginUserId = User.Identity.GetUserId(); 
     var searchLoginUserInfoId = from m in db.UserInfos 
            where 
             m.UserID == loginUserId 
            select m; 
     foreach (var c in searchLoginUserInfoId) 
     { 
      loginUserInfoId = c.UserInfoID; 
     } 
     return loginUserInfoId; 
    } 

,並收到您的登錄ID喜歡

Guid loginUserInfoId = getLoginUserInfoId(); 
0

這是我的代碼片段,我在那裏用1的DbContext來管理的一個例子,標識和型號 - 第一類。

Asuming你還沒有擴展你的IdentityUser模型,你可以用這個方法來獲取用戶名:

//Id in Identity is Guid; returning as string for simplicity 
public string GetUserId(string username) 
{ 
    var um = new UserManager<IdentityUser>(
       new UserStore<IdentityUser>(
        new IdentityDbContext())); 
    return um.FindByName(username).Id; 
} 

如果您有自定義屬性擴展您的身份模式,並因此創造了自己的模型

public class CustomUserModel : IdentityUser 
{ 
} 

...您需要更改上面的代碼相應

var um = new UserManager<CustomUserModel>(
      new UserStore<CustomUserModel>(
       new IdentityDbContext())); 

IdentityDbContext也是您的DbContext類。

希望這會有所幫助。

+0

當我重新在其他方法的用戶id作爲字符串um = GetUserId; 我收到錯誤無法將方法group'getuserid'轉換爲非委託類型字符串 –

+0

我不明白這一點。 – Marco

+0

我希望登錄用戶名在控制器的其他方法中被調用,並獲得登錄用戶ID並將其值發送到其他表 –

0

這解決我的問題

var LoginuserId=User.Identity.GetUserId();