Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext in WCF

I have written a simple REST API in WCF, and the authentication mechanism uses an API key. Once the client submits the API key in the request header, I check it on the server side (in the BaseService class overriding the ProcessRequest() method of RequestInterceptor class) as follows:

public partial class BaseService : RequestInterceptor
{
    public BaseService() : base(false) { }

    #region Process Request
    public override void ProcessRequest(ref RequestContext requestContext)
    {
        if (IsValidApiKey(requestContext))
           //put some values in HttpContext object.

     }

...

Now I have enabled aspnet compatibility in my REST services, but I still cannot access HttpContext object in the ProcessRequest override above. Note that HttpContext is accessible from inside a service method, but not in the ProcessRequest method.

Any ideas why?

like image 414
Rajesh Kumar Avatar asked Feb 04 '11 16:02

Rajesh Kumar


3 Answers

The HttpContext is probably initialized much later in the WCF channel stack. Remember that a channel interceptor runs in the channel stack before anything else, and just after the message has been received from the Http channel listener. What do you need to get access to the HttpContext from a request interceptor ?. The Http Request is available as a property in the message associated to the requestContext. You can also add store some values in the property bags available in the message as well.

Thanks Pablo.

like image 62
Pablo Cibraro Avatar answered Oct 25 '22 09:10

Pablo Cibraro


I have solved my problem by adding following code:

private HttpContext _httpContext;
public BaseService()
        : base(true)
    {
        _httpContext = HttpContext.Current;            

    }

After doing this I am able to access HttpContext object in the ProcessRequest method.

like image 37
Rajesh Kumar Avatar answered Oct 25 '22 11:10

Rajesh Kumar


However you should notice that HttpContext.Current is not thread safe and what is set up with one thread could be modified by another one.

For example two request come to your service. You put some value to the HttpContext in the RequestInterceptor for the first request. The second request waits till the first request is not finished with RequestInterceptors. If the first request finish with RequestInterceptors and is passed to you service the second request enters RequestInterceptors and can access to the HttpContext set up by the first request if the first request is not finished. It's a kind of problems I have encountered.

like image 1
Tomasz Jaskuλa Avatar answered Oct 25 '22 09:10

Tomasz Jaskuλa