在MVC-6中扩展ClaimsPrincipal和ClaimsIdentity类

mik*_*kal 4 c# asp.net-core-mvc asp.net-core

我一直想把这件事弄清楚几天,但不得不转向你们(再次).

正如标题所说,我想实现我的自定义ClaimsPrincipal和ClaimsIdentity,以便我可以将更多属性附加到我的Identity-instance.

我之前在MVC-5中已经使用Global.asax.cs和继承的BaseController完成了这个.在MVC-6中,似乎startup.cs将成为此的切入点,但我无法弄明白.

这是我的两个班级:

public class BaseIdentity : ClaimsIdentity
{
    public Guid UserId { get; set; }
    public Guid OrgId { get; set; }
    public string OrgName { get; set; }

    public BaseIdentity()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

和..

public class BasePrincipal : ClaimsPrincipal
{
    private readonly BaseIdentity _identity;

    public BasePrincipal(BaseIdentity identity)
    {
        _identity = identity;
    }

    public new BaseIdentity Identity
    {
        get { return _identity; }
    }
}
Run Code Online (Sandbox Code Playgroud)

在创建/检索Auth cookie时,如何使用这些类而不是默认值?

有一种方法叫做IApplicationBuilder.UseClaimsTransformation(),但找不到任何关于如何使用它的文档 - 如果它甚至适用于这种情况?

在这一点上非常感谢!:)

顺便说一句:我想指出,一周前,当我第一次遇到这个挑战时,我就问了一个类似的问题.我得到了答案,但这是我必须解决的问题,以使我的网站可用于MVC-6.

Fre*_*red 5

我使用扩展方法而不是继承来完成此操作.

public static class PrincipalExtensions
{
    public static string GetEmployeeNumber(this ClaimsPrincipal claimsPrincipal)
    {
        return claimsPrincipal.FindFirstValue("EmployeeNumber");
    }
}
Run Code Online (Sandbox Code Playgroud)