【问题标题】:ASP NET Core: Overwrite Username of HttpContextASP NET Core:覆盖 HttpContext 的用户名
【发布时间】:2017-07-26 19:47:36
【问题描述】:

有没有办法通过中间件在 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 中调用它,以便在请求期间用户名始终是“匿名的”。

有没有办法做到这一点?

【问题讨论】:

    标签: c# asp.net-core asp.net-identity


    【解决方案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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多