如何在WebApi请求中获取控制器名称?

时间:2016-08-09 13:07:30

标签: c# asp.net .net asp.net-web-api

我有一个logging.cs类,在我的WebApi项目中用于记录有关传入请求的信息。

该类是从我的Global.asax中的Application_BeginRequest()方法触发的。 我需要在请求中获取Controller名称和Authorization标头。怎么办?

我一直在玩HttpRequest Request对象,但我似乎无法完全理解我需要的东西。 (虽然Http请求的方法看起来很容易!!)

对于Authorization标题,我认为它就像“Request.Headers [”Authorization“];”但是现在这个回来是空的。

我的代码如下,任何方向或建议都将不胜感激。 -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);
            }
        }
    }
}

3 个答案:

答案 0 :(得分:5)

您应该为日志记录实现操作过滤器。这样您就可以通过HttpActionContext参数

访问控制器名称

Api控制器:

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

过滤

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

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
    }
}

您可以装饰需要使用[Logger]进行日志记录的每个方法,或者在控制器级别进行操作,以记录在该控制器内发生的每个调用。最后,您可以使操作过滤器全局,以便每次运行在你的项目中调用任何动作。

答案 1 :(得分:2)

如果需要在Controller动作中获取控制器名称,则可以使用

this.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName

答案 2 :(得分:0)

类似于Sin的答案,但对于ASP.Net Core 3.1:

 using System.Linq;

 ... 

 private void button3_Click(object sender, EventArgs e)
 {
   Label testLabel = tableLayoutPanel1
     .Controls
     .Find("test_1", true)
     .OfType<Label>()
     .FirstOrDefault();

   MessageBox.Show(testLabel?.Text ?? "Label not found");
 }