2016-04-24 38 views
3

我試圖使用HttpContext.Current.User與我自己的類繼承IPrincipal。我不完全確定爲什麼..如何將HttpContext.Current.User作爲mvc中的自定義主體c#

var lIdentity = new UserIdentity(lFormsTicket); 
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray(); 
var lPrincipal = new GenericPrincipal(lIdentity, lRoles); 

System.Web.HttpContext.Current.User = lIdentity; 

我剛剛設置它後,它的作品。但是如果我在網站上做了另一個請求,它說它不能投射它。我在這裏錯過了什麼嗎?

回答

1

要設置UserIIdentity當它應該是IPrincipal

var lIdentity = new UserIdentity(lFormsTicket); 
var lRoles = lAuthUser.Roles.Select(x => x.Role.ToString()).ToArray(); 
var lPrincipal = new GenericPrincipal(lIdentity, lRoles); 

System.Web.HttpContext.Current.User = lPrincipal; 

您可能需要使用自己的自定義IPrincipal

public class UserPrincipal : IPrincipal { 
    string[] roles; 

    public UserPrincipal (IIdentity identity, param string[] roles) { 
     this.Identity = identity; 
     this.roles = roles ?? new string[]{ }; 
    } 

    public IIdentity Identity { get; private set; } 

    public bool IsInRole(string role) { 
     return roles.Any(s => s == role); 
    } 
} 

我不知道,如果應用程序將如投訴它可能期望派生類型爲ClaimsPrincipal

+0

這也不起作用。 (BO.Security.UserIdentity)User.Identity導致同樣的問題。 –

+1

拋出錯誤在哪裏。同時顯示你的'BO.Security.UserIdentity'類,因爲我們需要知道它繼承了什麼。請注意,'GenericPrincipal.Identity' =>'獲取由當前System.Security.Principal.GenericPrincipal'表示的用戶的System.Security.Principal.GenericIdentity。 – Nkosi

+0

錯誤正在被拋出無處不在我試圖將User.Identity作爲我的自定義用戶標識除了我設置用戶的方法(在登錄中)之外。 UserIdentity繼承自IIdentity –

相關問題