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?


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.


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.


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.

链接地址: http://www.djcxy.com/p/4568.html

上一篇: 如何通过make在批量Sweave调用中使用cacheSweave?

下一篇: WCF中的HttpContext