current OperationContext is null in WCF Windows Service

后端 未结 5 1610
感情败类
感情败类 2020-12-19 03:20

I am trying to set up a Publish/Subscribe system using WCF and where the WCF server is in a Windows service. The binding is net.TCP. The service is providing a \"Subscribe

相关标签:
5条回答
  • 2020-12-19 04:05

    I had a similar issue: in my case when the InstanceContextMode was set to Single the WebOperationContext.Current was null in the constructor. However it was available within the services/classes methods.

    0 讨论(0)
  • 2020-12-19 04:11

    In the client code neither proxy created not channel factory. Service class instance is created as a class library.

    You should consume service as below code

     ServiceCallback serviceCallback = new ServiceCallback();
     InstanceContext instanceContext = new InstanceContext(serviceCallback);
    
     var pubsubProxy = new PubSubProxy.WcfPublisherContractClient(instanceContext);
     pubsubProxy.Subscribe();
    

    And when the service is running, OperationContext is created and you can access OperationContext.Current

    0 讨论(0)
  • 2020-12-19 04:14

    I've faced this issue and non of the solutions worked and Most Important thing is if you're using

    async await 
    OperationContext.Current; will be null
    

    My usage is to get Ip so used it like this before any awaitable call

    var clientIpAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;
    

    After the first await statement in your async service operation, OperationContext.Current could be null because the rest of the method body may be running on a different thread (and OperationContext does not flow between threads

    So to get it you can write your code before any awaitable action

    May be it'll help someone :)

    0 讨论(0)
  • 2020-12-19 04:20

    As discussed in the comments, if you directly create an instance of the service type - as opposed to a WCF proxy/clientchannel - and then you call a method on it, there is no OperationContext. WCF provides an OperationContext instance when your operation is running within a service.

    0 讨论(0)
  • 2020-12-19 04:20

    In my case it was me being stupid...

    I tried to set

     callback = OperationContext.Current.GetCallbackChannel<IWcfSubscriberContract>();
    

    In the CALLBACK function, instead of the server side funciton... When in callback function - obviously there's no current context.

    0 讨论(0)
提交回复
热议问题