How to get controller name in WebApi Request?

12,462

Solution 1

You should implement an action filter for logging.That way you will be able to access the controller name through the HttpActionContext parameter

Api Controller:

public class LeadsController : ApiController
{
    [Logger]
    public List<string> Get()
    {
        return new List<string> { "Lead 1", "Lead 2", "Lead 3", "Lead 4","Lead 5" };
    }
}

Filter:

public class Logger : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        string controllerName = 
            actionContext.ControllerContext.ControllerDescriptor.ControllerName;
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
    }
}

You can decorate each method that needs logging with [Logger] or do it at the controller level to log every single call that happens inside that controller.Lastly, you can make your action filter global so that it will run everytime any action is called inside your project.

Solution 2

Similar to Sin's answer but for ASP.Net Core 3.1:

var myControllerName = ControllerContext.ActionDescriptor.ControllerName;

Solution 3

Just in case if you need to get the controller name in the Controller action, then you can use

this.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName

Share:
12,462
Jason Livengood
Author by

Jason Livengood

Updated on June 26, 2022

Comments

  • Jason Livengood
    Jason Livengood almost 2 years

    I have a logging.cs class that is used in my WebApi project to log information about the incoming request.

    The class is triggered from my Application_BeginRequest() method in my Global.asax. I need to get the Controller name and the Authorization header in the request . How to do ?

    I keep playing with the HttpRequest Request object but I cannot seem to sort of harness what it is I need exactly. (Although method of the Http request seems easy enough!!)

    For the Authorization header I would think it would be as simple as "Request.Headers["Authorization"];" however this comes back as null currently.

    My code is below, any direction or advice would be greatly appreciated. -Jason

    namespace WCAPI.BLL
    {
        public class logging_2
        {
            private static HttpRequest Request
            {
                get { return HttpContext.Current.Request; }
            }
    
            private static HttpResponse Response
            {
                get { return HttpContext.Current.Response; }
            }
    
            public static void LogWcapiRequest(BLL.DebugTmr tmr)
            {
                if (tmr.EventType == DebugTmr.EventTypes.Null) { return; }
    
                try
                {
                    Services.AFSILog log = new Services.AFSILog();
                    log.Level = Services.LogLevels.Info;
                    log.SourceSystem = ANACore.AMTConfig.GetConfigurationValue("ConsoleLogSourceSystem");
                    if (Request.Url.IsLoopback) { log.SourceSystem += "_" + System.Environment.MachineName; }
                    log.Stamp = DateTime.Now;
                    log.Message = tmr.FormatedMsg;
                    log.Category = tmr.EventType.ToString();
    
    
                    List<Services.LogData> dets = new List<Services.LogData>();
                    dets.Add(new Services.LogData { DataType = Services.ParameterDataTypes.Int, DataKey = "Duration", DataValue = tmr.ElapsedMs.ToString() });
    
                    //This appears to be easy!! 
                    var meth = Request.HttpMethod;
                    dets.Add(new Services.LogData { DataType = Services.ParameterDataTypes.Int, DataKey = "Method", DataValue = meth });
    
                    //Now how do I get Authorization Header and Controller name ?
    
    
                    foreach (BLL.DebugTmr.Waypoint wp in tmr.Waypoints)
                    {
                        dets.Add(new Services.LogData
                        {
                            DataType = Services.ParameterDataTypes.Int,
                            DataKey = wp.Name + "Ms",
                            DataValue = wp.ElapsedMs.ToString()
                        });
                    }
    
                    log.Parameters = dets.ToArray();
                    // This is what actually writes to the log I just need add Authorization header and Controller name to my log object
                    SaveLog(log);
                }
                catch (Exception ex)
                {
                    Debug.Print("Page log create failed : {0}", ex.Message);
                }
            }
        }
    }
    
  • Jason Livengood
    Jason Livengood over 7 years
    Thank you so much ! I have it to where I can get the controller name now. Still trying to register my logging class as a global filter.
  • Denys Wessels
    Denys Wessels over 7 years
    Please remember to mark as answered if it helped you
  • Onkel Toob
    Onkel Toob over 2 years
    Also applies to .NET 5 and .NET 6