gpt4 book ai didi

c# - 如何使用 httpcontextaccessor 在 .net core 中获取 Controller 和操作名称

转载 作者:行者123 更新时间:2023-12-05 09:13:34 36 4
gpt4 key购买 nike

现在我正在努力将 .Net MVC 应用程序转换为 .Net Core 应用程序

要记录我们在 MVC 中使用“HttpContext”的事件

LoggerException loggerException = new LoggerException();
loggerException.ApplicationName = "Service";
loggerException.Level = logLevel;
loggerException.Timestamp = DateTime.UtcNow.ToString();
loggerException.UserController = HttpContext.Current.Request.Url.Segments[2];
loggerException.Action = HttpContext.Current.Request.Url.Segments[3];
loggerException.IpAddress = HttpContext.Current.Request.UserHostAddress;

在 .Net Core 中,“IHttpContextAccessor”替代了“HttpContext”。我无法获取用户 Controller 和操作

我当前的 .net 核心代码

LoggerException loggerException = new LoggerException();
loggerException.ApplicationName = appName;
loggerException.Level = logLevel;
loggerException.Timestamp = DateTime.UtcNow;
//loggerException.UserController = httpContextAccessor.HttpContext != null ? httpContextAccessor.HttpContext.User.ToString() : string.Empty;
//loggerException.Action = httpContextAccessor.HttpContext != null ? httpContextAccessor.HttpContext. : string.Empty;
loggerException.IpAddress = httpContextAccessor.HttpContext != null ? httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString() : string.Empty;

最佳答案

获取RouteData对于 IActionContextAccessor.ActionContext 中的当前请求属性,然后获取如下所示的 Controller 和操作名称。

var rd = actionContextAccessor.ActionContext.RouteData;
string currentController = rd.Values["controller"].ToString();
string currentAction = rd.Values["action"].ToString();

关于c# - 如何使用 httpcontextaccessor 在 .net core 中获取 Controller 和操作名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007002/

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