有没有办法通过中间件在ASP NET Core应用程序中设置用户名?
我创建了AnonymousUserMiddleware
:
public AnonymousUserMiddleware(RequestDelegate next, HttpContextCurrentClaimsPrincipalAccessor currentClaimsPrincipalAccessor, ILogger<AnonymousUserMiddleware> logger)
{
_next = next;
_currentClaimsPrincipalAccessor = currentClaimsPrincipalAccessor;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
_currentClaimsPrincipalAccessor?.Current?.Identity?.Name = "anonymous";
await _next.Invoke(context);
}
catch (Exception ex)
{
_logger.LogError(1, ex, "Exception");
throw ex;
}
}
但这不起作用,因为Name
是一个只读字段。
我想在开发人员模式下在Startup.cs
中调用它,以便在请求期间用户名始终是“匿名的”。
有没有办法实现这个目标?
答案 0 :(得分:1)
您可以构建自己的ClaimsPrincipal并将实例分配给HttpContext。例如:
public async Task Invoke(HttpContext context)
{
try
{
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "anonymous", "http://www.w3.org/2001/XMLSchema#string"));
var principal = new ClaimsPrincipal();
principal.AddIdentity(identity);
context.User = principal;
await _next.Invoke(context);
}
catch (Exception ex)
{
_logger.LogError(1, ex, "Exception");
throw ex;
}
}