Search code examples
c#.netasp.net-mvcasp.net-web-apipostsharp

Accessing a request header from inside a custom PostSharp attribute


I'm trying to access a HttpRequestMessage from inside a custom PostSharp attribute.

In my Web API I could do it like this:

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

This doesn't seem to work outside of the API controller.

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

Solution

  • I found I can access the headers this way:

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