asp.net-mvc-5 – MVC 5 – 向用户添加声明
发布时间:2020-05-24 10:28:52 所属栏目:asp.Net 来源:互联网
导读:我正在开发一个MVC 5互联网应用程序,并使用Identity 2.1. 在用户登录后,我如何向用户添加声明,我知道用户名? 这是我有的: public void AddClaimToUser(string userName, string type, string value ){ var AuthenticationManager = HttpContext.Current.Get
|
我正在开发一个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(); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET框架中的异步页面 – 其他线程在哪里,如何重新连接?
- asp.net-mvc – 有没有人知道让Ninject 2在ASP.NET MVC中工
- asp.net – 在项目之间共享aspx页面
- asp.net-mvc – 如何将KendoUI DropDownListFor绑定到ViewD
- asp.net-mvc-3 – 如何在自定义编辑器模板中获取模型的字段
- ASP.NET MVC 4 / Web API – 为Accepts插入Razor渲染器:te
- asp.net-mvc – MVC 4忽略DefaultModelBinder.ResourceClas
- asp.net-mvc-3 – 可以添加到显示/ EditorTemplates ASP.NE
- asp.net – 如何在aspx文件中创建区域?
- asp.net – web.config在文件夹允许全部或没有用户身份验证
推荐文章
站长推荐
- asp.net-mvc – 用于局部视图的ASP.NET MVC 3控制
- asp.net – 我可以同时拥有Controller和ApiContr
- 在Build上自动停止/重新启动ASP.NET开发服务器
- asp.net-mvc – 没有找到与名为“User”的控制器
- asp.net-mvc – ASP.net MVC – 我可以告诉Html.
- asp.net-mvc – 改进ASP.NET MVC启动性能
- asp.net-mvc – ASP.NET MVC – 什么是UrlRoutin
- asp.net-mvc – 如何缓存FileContentResult的性能
- 如何获取ASP.NET应用程序的完整虚拟路径
- asp.net – 我可以使用一种模式来编辑MVC3应用程
热点阅读
