gpt4 book ai didi

asp.net - 为每个请求记录客户端 ip - kestrel 的访问日志

转载 作者:行者123 更新时间:2023-12-05 02:17:31 25 4
gpt4 key购买 nike

有没有用 kestrel 托管记录客户端 ips 的方法?我在应用程序设置中指定了 DEBUG 日志级别,但它仍然只显示正在请求的服务器路径,而不是来自谁。

我知道客户端 ip 可以从每个 api 中的 HttpContext 结构中获取,但我想要的只是通过框架记录它,这样我就可以节省在每个 api 中添加相同的函数。

dbug: Microsoft.AspNetCore.Server.Kestrel[1]
Connection id "0HL9L7IJ7JLIV" started.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://192.168.1.110:2180/ <====== it logs the server path
dbug: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[9]
AuthenticationScheme: Bearer was not authenticated.
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'default' and template '{controller}/{action}'.
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action CH.Api.Controllers.HomeController.Index (CH)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method CH.Controllers.HomeController.Index (CH) with arguments ((null)) - ModelState is Valid
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
...
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
Connection id "0HL9L7IJ7JLIV" completed keep alive response.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 160.2879ms 200 text/plain; charset=utf-8
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv[6]
Connection id "0HL9L7IJ7JLIV" received FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel[10]
Connection id "0HL9L7IJ7JLIV" disconnecting.
dbug: Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv[7]
Connection id "0HL9L7IJ7JLIV" sending FIN.
dbug: Microsoft.AspNetCore.Server.Kestrel[2]
Connection id "0HL9L7IJ7JLIV" stopped.

最佳答案

也许您可以创建一个自定义中间件,仅用四行记录每个请求:

app.Use(async (context, next) =>
{
Console.WriteLine($"[{context.Connection.RemoteIpAddress}] | {context.Request.Path}");
await next.Invoke();
});

输出:

[127.0.0.1] | /
[127.0.0.1] | /About
[127.0.0.1] | /Post

或将 context.Request.Path 替换为 context.Request.GetDisplayUrl() 以查看完整的 URL:

[127.0.0.1] | http://127.0.0.1:5000/Post?id=1

关于asp.net - 为每个请求记录客户端 ip - kestrel 的访问日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com