【发布时间】:2021-04-01 15:19:02
【问题描述】:
我想在 asp.net core 中添加自定义 HttpContextAccessor 服务,
这是正确的方法吗:
在 ConfigureService 方法中:
var env = services.BuildServiceProvider().GetRequiredService<Microsoft.AspNetCore.Hosting.IHostingEnvironment>();
然后添加海关声明(这些将由 anther 类提取)。
if(env.IsDevelopment())
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "test"));
claims.Add(new Claim(ClaimTypes.Role, "Operator"));
claims.Add(new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", "af4ab79d-f75c-44be-b8dd-test"));
claims.Add(new Claim("CompanyName", "test"));
services.AddSingleton<IHttpContextAccessor>(sp => new DefaultHttpContext()
{
User = new ClaimsPrincipal(new ClaimsIdentity(claims)),
});
}
这样,IHttpContextAccessor 和 DefaultHttpContext 的类型不匹配,有没有办法解决这个问题或如何正确解决?
【问题讨论】:
-
你的场景是什么?其实我认为你需要在中间件中添加对 httpcontext 用户的声明。
-
我该怎么做?好吧,我的情况是我有一个 API 通过 Azure AD 进行授权,对于开发环境,我喜欢有一个硬编码的用户,因为我在其他类中使用 IHttpContextAccessor 来提取用户声明/
标签: c# asp.net-core httpcontext