Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access HttpContext inside WCF RequestInterceptor

I am using the WCF REST stater kit to build a plain xml over HTTP service. As part of this Im using a RequestInterceptor to do authentication. Inside of the RequestInterceptor I have access to a System.ServiceModel.Channels.RequestContext object from which i can get the request url, querystring params and other helpful things. What I cannot work out is how to get access to the HttpContext of the request. I have several things stored in the HttpContext which I want to access inside the requestInterceptor but Im struggling to get to them. When I use the quickwatch inside Visual Studio I can see that it is there buried inside private members of the requestContext. Can somebody show me how to access the HttpContext, perhaps using reflection on the RequestContext object?

like image 967
Dav Evans Avatar asked Oct 27 '09 11:10

Dav Evans


1 Answers

You can access ASP.NET's HttpContext inside any WCF service hosted in ASP.NET as long as you turn on compatibility. This is done in two steps:

  1. Apply the AspNetCompatibilityRequirementsAttribute to your service class and set the RequirementsMode property to Required
  2. Make sure you enable compatibility by configuring the following:

    <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled=”true” />
    </system.serviceModel>
    

Once you've done that, you can access the current HttpContext instance at any time using the static Current property. For example:

foreach(HttpCookie cookie in HttpContext.Current.Request.Cookies)
{
    /* ... */
}

Note that enabling integration with the ASP.NET runtime does incur some additional overhead for each request, so if you don't need it you can save some performance by not enabling it and just using the System.ServiceModel.Web runtime instead. You have access to pretty much all the information you need using the HttpRequestResponseMessageProperty and HttpResponseMessageProperty classes.

For more information on the subject, see this section of MSDN titled WCF and ASP.NET.

like image 74
Drew Marsh Avatar answered Oct 24 '22 05:10

Drew Marsh