C# 为非web请求设置标识

C# 为非web请求设置标识,c#,asp.net,C#,Asp.net,我想为非web请求设置标识。目前我正在使用FormsAuthentication,并通过此user.identity.Name获取用户标识。现在我必须让用户通过API登录。我有该用户的用户名/密码,如何设置该用户的身份 您需要创建自己的IPrincipal和IIdentity实现,然后在对HttpContext.User进行身份验证后将其分配给HttpContext.User。在非web环境中,身份在线程上设置,可以通过以下方式访问: Thread.CurrentPrincipal.Identi

我想为非web请求设置标识。目前我正在使用FormsAuthentication,并通过此user.identity.Name获取用户标识。现在我必须让用户通过API登录。我有该用户的用户名/密码,如何设置该用户的身份

您需要创建自己的IPrincipal和IIdentity实现,然后在对HttpContext.User进行身份验证后将其分配给HttpContext.User。

在非web环境中,身份在线程上设置,可以通过以下方式访问:

Thread.CurrentPrincipal.Identity
您可以使用它来操纵标识,或者按照Vadim的建议,使用您自己的自定义主体完全覆盖标识

此代码段取自
System.Web.Security.Membership
类,该类在Web和非Web环境中与主体一起工作,并演示如何将两者结合使用

public static string GetCurrentUserName()
{
    if (HostingEnvironment.IsHosted)
    {
        HttpContext current = HttpContext.Current;
        if (current != null)
        {
            return current.User.Identity.Name;
        }
    }
    IPrincipal currentPrincipal = Thread.CurrentPrincipal;
    if ((currentPrincipal != null) && (currentPrincipal.Identity != null))
    {
        return currentPrincipal.Identity.Name;
    }
    return string.Empty;
}
遵循以下步骤: