5

MVC プロジェクト用に単純なIIdentityandを開発しました。これをオーバーライドして、適切な型の値を返しIPrincipalたいと思います。UserUser.Identity

これが私のカスタムアイデンティティです:

public class MyIdentity : IIdentity
{
    public MyIdentity(string name, string authenticationType, bool isAuthenticated, Guid userId)
    {
        Name = name;
        AuthenticationType = authenticationType;
        IsAuthenticated = isAuthenticated;
        UserId = userId;
    }

    #region IIdentity
    public string Name { get; private set; }
    public string AuthenticationType { get; private set; }
    public bool IsAuthenticated { get; private set; }
    #endregion

    public Guid UserId { get; private set; }
}

これが私のカスタムプリンシパルです:

public class MyPrincipal : IPrincipal
{
    public MyPrincipal(IIdentity identity)
    {
        Identity = identity;
    }


    #region IPrincipal
    public bool IsInRole(string role)
    {
        throw new NotImplementedException();
    }

    public IIdentity Identity { get; private set; }
    #endregion
}

これが私のカスタム コントローラーです。Userカスタム プリンシパル タイプを返すようにプロパティを正常に更新しました。

public abstract class BaseController : Controller
{
    protected new virtual MyPrincipal User
    {
        get { return HttpContext == null ? null : HttpContext.User as MyPrincipal; }
    }
}

User.Identityカスタム ID タイプを返すのと同じようにするにはどうすればよいですか?

4

2 に答える 2

3

クラスに明示的に実装IPrincipalし、type の独自のプロパティをMyPrincipal追加できます。IdentityMyIdentity

public class MyPrincipal : IPrincipal 
{
    public MyPrincipal(MyIdentity identity)
    {
        Identity = identity;

    }

    public MyIdentity Identity {get; private set; }

    IIdentity IPrincipal.Identity { get { return this.Identity; } }

    public bool IsInRole(string role)
    {
        throw new NotImplementedException();
    }
}
于 2012-11-20T15:25:10.897 に答える
1

明示的なキャストなしではできないことを求めています

public class MyClass
{
    private SomeThing x;
    public ISomeThing X { get { return x; } }
}

を呼び出すと、ではなくMyClass.Xが返されます。明示的なキャストを行うことができますが、それは少し不器用です。ISomeThingSomeThing

MyClass myClass = new MyClass();
SomeThing someThing = (SomeThing)(myClass.X);

理想的には、格納する値はIPrincipal.Name一意です。"jdoe" がアプリケーション内で一意でないIPrincipal.Name場合、ユーザー ID を格納した方がプロパティはより適切になります。あなたの場合、それは GUID のようです。

于 2012-11-20T15:13:48.863 に答える