栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在ASP.NET Identity中更新声明?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在ASP.NET Identity中更新声明?

我基于给定的ClaimsIdentity创建了一种扩展方法来添加/更新/读取声明

namespace Foobar.Common.Extensions{    public static class Extensions    { public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value) {     var identity = currentPrincipal.Identity as ClaimsIdentity;     if (identity == null)         return;     // check for existing claim and remove it     var existingClaim = identity.FindFirst(key);     if (existingClaim != null)         identity.RemoveClaim(existingClaim);     // add new claim     identity.AddClaim(new Claim(key, value));     var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;     authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); } public static string GetClaimValue(this IPrincipal currentPrincipal, string key) {     var identity = currentPrincipal.Identity as ClaimsIdentity;     if (identity == null)         return null;     var claim = identity.Claims.FirstOrDefault(c => c.Type == key);     return claim.Value; }    }}

然后使用它

using Foobar.Common.Extensions;namespace Foobar.Web.Main.Controllers{    public class HomeController : Controller    {        public ActionResult Index()        { // add/updating claims User.AddUpdateClaim("key1", "value1"); User.AddUpdateClaim("key2", "value2"); User.AddUpdateClaim("key3", "value3");        }        public ActionResult Details()        { // reading a claim var key2 = User.GetClaim("key2");        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452039.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号