如何使用httpcontextaccessor在.net核心中获取控制器和动作名称

时间:2019-05-06 14:15:25

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

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

要记录事件,我们在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中的

替代了“ HttpContext”。 我无法获得用户控制器和操作

我当前的.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;

2 个答案:

答案 0 :(得分:2)

RouteData属性中获取当前请求的IActionContextAccessor.ActionContext,然后获取如下的控制器和动作名称。

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

答案 1 :(得分:1)

基于 Xueli Chen 的回答,如果您想从 BaseController 获取控制器和操作名称,请使用 filterContext 如下:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       string controller = filterContext.RouteData.Values["controller"].ToString();
       string action = filterContext.RouteData.Values["action"].ToString();

       //your other code here...
       ...
       base.OnActionExecuting(filterContext);
    }

这适用于 MVC Core 3.1。对我来说。