HttpContext.Current is null on the initial request.

Topics: Web Api
Nov 2, 2011 at 11:09 AM

Hi,

i am using a custom message handler for api verification. While trying to accessHttpContext.Current inside the SendAsync() method its returning null value during the initial request, but its been populated in the further requests. I need access to the UserHostIPAddress of the request property.

Thanks in advance

Nov 2, 2011 at 12:39 PM

There are a few other topics about this.  Like you mentioned, DelegatingHandler runs async and is thus not guaranteed to run on the same thread as the request thread, meaning it will not get the Http context.

I really hope MS will fix this somehow, but until then your only option (afaik) is to go with a HttpOperationHandler instead of DelegatingHandler.

Nov 2, 2011 at 4:39 PM

You should be able to avoid using any of the context objects such as HttpContext or OperationContext as now in Preview 5 much of that information is in the Properties collection on the HTTPRequestMessage.  See the following example of how to get the IPAddress

        [WebGet(UriTemplate="ResourceA")]
        public HttpResponseMessage GetResourceA(HttpRequestMessage httpRequestMessage) {

            var prop = httpRequestMessage.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
         
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(prop.Address);
            return response;
        }

Jun 15, 2012 at 9:59 PM

Darrel,

I know this is an old post, but I'm on Preview 6 (we haven't migrated to ASP.NET WebApi yet) and I'm passing my api token (after auth granted) through the request properties.

This token contains encrypted information about the destination of the operation: tenant, login, etc. Is there a way in Preview 6 to set this token in HttpContext.Current.Items so it is available across the request w/o having to do it on every resource operation?

Thanks,

Raciel