asp.net-mvc-5 – MVC 5 – 向用户添加声明

我正在开发一个MVC 5互联网应用程序,并使用Identity 2.1.

用户登录后,我如何向用户添加声明,我知道用户名

这是我有的:

public void AddClaimToUser(string userName,string type,string value )
{
    var AuthenticationManager = HttpContext.Current.GetowinContext().Authentication;
    var Identity = new ClaimsIdentity(userName);
    Identity.AddClaim(new Claim(type,value));
    AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity),new AuthenticationProperties { IsPersistent = true });
}

但是,在我调用方法并检查用户的声明后,未列出添加的声明.

这是我用来在控​​制器中获取声明的代码

var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;

提前致谢.

解决方法

首先,你必须在IdentityModels.cs类下创建一个添加声明的方法.就像这样,在下面的代码中我创建了一个对CompanyId的声明.
public class ApplicationUser : IdentityUser
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public bool IsActive { get; set; }
  public int? CompanyId { get; set; }


public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{

  var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);

  userIdentity.AddClaim(new Claim("CompanyId",(this.CompanyId + "" ?? "0")));

  return userIdentity;
}}

在编写上面的代码之后,您需要在IdentityConfig.cs中再编写一个方法

public static class IdentityExtensions{
public static int CompanyId(this IIdentity identity)
{
 return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value);
}}

在此之后,只需输入即可在任何控制器中获取您创建的声明.

int companyId = User.Identity.CompanyId();

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....