2016-04-24 11 views
3

IPrincipalを継承する自分のクラスでHttpContext.Current.Userを使用しようとしています。私は確信していません。mvcのカスタムプリンシパルとしてHttpContext.Current.Userを取得する方法#

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

あなたはそれが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); 
    } 
} 

を使用する必要がありますする必要があるとき、私は、アプリケーションのように文句を言うのかはわからないIIdentityとしてUserを設定していますそれは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から継承します –

関連する問題