从自定义PostSharp属性中访问请求标头

时间:2016-10-08 04:22:48

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

我正在尝试从自定义PostSharp属性中访问HttpRequestMessage

在我的Web API中,我可以这样做:

string headerText = Request.Headers.GetValues("TestHeader").First();

这似乎不适用于API控制器之外。

[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public sealed class LogHeaderAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        // Log Web API request header info here
    }
}

1 个答案:

答案 0 :(得分:1)

我发现我可以通过这种方式访问​​标题:

[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public sealed class LogHeaderAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        ApiController apiController = (ApiController)args.Instance;
        var context = apiController.ControllerContext;
        HttpRequestHeaders headers = context.Request.Headers;

        // Use Web API request header info here
        string headerText = headers.GetValues("MyHeader").First();
    }
}