【问题标题】:How to get the id of the current user when logging web api requests via middleware通过中间件记录 web api 请求时如何获取当前用户的 id
【发布时间】:2019-11-05 07:10:58
【问题描述】:

我在中间件中有以下 Invoke 函数来记录 Web api 请求。它基于this example,并且运行良好。但是,我还想保存发送请求的当前用户的username

 public async Task Invoke(HttpContext httpContext, IApiLogService apiLogService)
 {
     try
     {
         _apiLogService = apiLogService;

         var request = httpContext.Request;
         if (request.Path.StartsWithSegments(new PathString("/api")))
         {
             var stopWatch = Stopwatch.StartNew();
             var requestTime = DateTime.UtcNow;
             var requestBodyContent = await ReadRequestBody(request);
             var originalBodyStream = httpContext.Response.Body;

             await SafeLog(requestTime,
                   stopWatch.ElapsedMilliseconds,
                   200,//response.StatusCode,
                   request.Method,
                   request.Path,
                   request.QueryString.ToString(),
                   requestBodyContent
                   );           
         }
         else
         {
             await _next(httpContext);
         }
     }
     catch (Exception ex)
     {
         await _next(httpContext);
     }
 }

但是,httpContextUser 属性似乎缺少用户信息。下面我分享它的内容。我想知道如何获取发送请求的用户的 ID。我没有使用 Windows 身份验证。有什么建议吗?

【问题讨论】:

  • 猜测,您的中间件在身份验证中间件之前运行。请问你能说明你是如何配置这两个的吗?
  • @John 非常感谢!你是对的 :) 我第一次使用中间件。我很高兴解决方案如此简单!

标签: c# asp.net asp.net-core asp.net-web-api middleware


【解决方案1】:

解释为什么会发生这种情况的关键点

httpContext 的 User 属性似乎缺少用户信息

是Startup类的Configure方法中中间件的顺序。 ASP.NET Core 请求管道处理通过按照它们在 Startup 类的 Configure 方法中放置的顺序运行中间件组件来工作。

因此,在将自定义中间件添加到 Startup 类的 Configure 方法中的管道 app.UseYourMiddleware(); 之前,您需要将 app.UseAuthentication(); 移动到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 2017-01-21
    • 2019-10-28
    • 1970-01-01
    • 2012-06-24
    • 2015-10-15
    • 2011-08-08
    • 2014-01-31
    相关资源
    最近更新 更多