Satti
Satti

Reputation: 559

How to get the controller and action names in .net core using httpcontextaccessor

Now I am working on converting .Net MVC app to .Net Core App

To Log the events we are using "HttpContext" in MVC

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;

in .Net Core "IHttpContextAccessor" is replacement for the "HttpContext". I am unable to get the User controller and Action

My Current .net Core Code

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;

Upvotes: 3

Views: 15312

Answers (2)

Saeed Nawaz
Saeed Nawaz

Reputation: 99

Building on Xueli Chen's answer, if you want to get the controller and action names from a BaseController, use the filterContext as so:

    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);
    }

This worked in MVC Core 3.1. for me.

Upvotes: 2

Xueli Chen
Xueli Chen

Reputation: 12725

Get the RouteData for the current request in the IActionContextAccessor.ActionContext Property , then get the controller and action name like below.

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

Upvotes: 9

Related Questions