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

Accessing a request header from inside a custom PostSharp attribute

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

在我的网站中 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
    }
}

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

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