C# 如何使用OWIN身份验证获取登录用户?

C# 如何使用OWIN身份验证获取登录用户?,c#,asp.net-mvc,owin,C#,Asp.net Mvc,Owin,myAccountController中的登录代码 var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, user.Name+" "+user.Surname)); claims.Add(new Claim(ClaimTypes.Role, role.Code)); var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticat

myAccountController中的登录代码

var claims = new List<Claim>();  
claims.Add(new Claim(ClaimTypes.Name, user.Name+" "+user.Surname));
claims.Add(new Claim(ClaimTypes.Role, role.Code));
var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, claimIdenties);
允许我访问以下属性:

  • 身份验证类型
  • 认证
  • Name//Claim.Name
如何设置像“Claim.ID”这样的ID并检索它

第二次编辑

Request.GetOwinContext().Authentication.User.Identity

这篇文章解决了我的问题。

Microsoft.AspNet.Identity.Core
NuGet包,在
Microsoft.AspNet.Identity
命名空间中,有一些扩展方法可以获取用户的ID和名称--请参阅

用法如下(从控制器):


你也可以这样写:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;

public class BaseController : Controller
{
    protected ApplicationUser CurrentUser
    {
        get { return System.Web.HttpContext.Current.GetOwinContext()
                    .GetUserManager<ApplicationUserManager>()
                    .FindById(System.Web.HttpContext.Current.User.Identity.GetUserId()); 
            }
    }

    //...
}
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.Owin;
使用System.Web;
使用System.Web.Mvc;
公共类BaseController:控制器
{
受保护的应用程序用户CurrentUser
{
获取{return System.Web.HttpContext.Current.GetOwinContext()
.GetUserManager()
.FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
}
}
//...
}
因此,您编写了一个
BaseController
,它继承自
Controller

然后,您的所有控制器将从
BaseController
继承;因此,您可以在所有控制器中使用
CurrentUser.Id

尝试以下替代方法:

var user = HttpContext.GetOwinContext().Authentication.User;

要获取
用户的名称

string name = HttpContext.GetOwinContext().Authentication.User.Identity.Name;

希望这有助于…

此.GetOwinContext().Authentication.User
?()因此,上面的评论将为您提供
权利要求。。。从这里您可以
principal.FindFirst(claimType)?.Value
,其中默认的
id
索赔类型(在aspnet标识中,很可能也是其他类型)是
”http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier“
string name = HttpContext.GetOwinContext().Authentication.User.Identity.Name;