c# – 在.net core 2.0中缓存声明
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在.net core 2.0中缓存声明,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1903字,纯文字阅读大概需要3分钟。
内容图文
到处看,但看起来我现在被卡住了.我在我的应用程序中使用Windows Active Directory进行身份验证.
对于授权,我正在使用索赔.在搜索有限的.net核心文档之后,这就是我的代码的样子.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPrincipal>(
provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
ClaimsTransformer.cs
class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
// call to database to get more claims based on user id ClaimsIdentity.Name
((ClaimsIdentity)principal.Identity).AddClaim(new Claim("now",DateTime.Now.ToString()));
return Task.FromResult(principal);
}
}
但问题是,每次请求都会调用此代码,并且每次都会从db加载声明,这绝对是错误的.有什么方法可以缓存它吗?我能够创建一个声明的cookie,并使用该cookie进行.net 4.0中的任何进一步调用.我似乎无法找到核心方式.我检查的任何文档都不完整,或者不包括我的场景.我可以在我的申请中进一步声明文档如何在这里说:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims
但没有提及缓存声明.
谁在同一条船上?还是知道出路呢?
解决方法:
您可以在ClaimsTransformer构造函数中注入IMemoryCache服务.
using Microsoft.Extensions.Caching.Memory;
public class ClaimsTransformer : IClaimsTransformation
{
private readonly IMemoryCache _cache;
public ClaimsTransformer(IMemoryCache cache)
{
_cache = cache;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var cacheKey = principal.FindFirstValue(ClaimTypes.NameIdentifier);
if (_cache.TryGetValue(cacheKey, out List<Claim> claims)
{
((ClaimsIdentity)principal.Identity).AddClaims(claims);
}
else
{
claims = new List<Claim>();
// call to database to get more claims based on user id ClaimsIdentity.Name
_cache.Set(cacheKey, claims);
}
return principal;
}
}
内容总结
以上是互联网集市为您收集整理的c# – 在.net core 2.0中缓存声明全部内容,希望文章能够帮你解决c# – 在.net core 2.0中缓存声明所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。