gpt4 book ai didi

c# - 覆盖用户的 IIdentity 属性

转载 作者:太空狗 更新时间:2023-10-29 23:24:37 25 4
gpt4 key购买 nike

我为我的 MVC 项目开发了一个简单的 IIdentityIPrincipal,我想覆盖 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; }
}

这是我的自定义委托(delegate)人:

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
}

这是我的自定义 Controller ,我成功更新了 User 属性以返回我的自定义主体类型:

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

如何以相同的方式让 User.Identity 返回我的自定义身份类型?

最佳答案

您可以在您的 MyPrincipal 类中显式实现 IPrincipal,并添加您自己的 Identity 类型的 MyIdentity 属性.

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();
}
}

关于c# - 覆盖用户的 IIdentity 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13475837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com