OperationContext.Current is null after first await when using async/await in WCF service

前端 未结 7 604
礼貌的吻别
礼貌的吻别 2020-12-02 22:59

I am using async/await pattern in .NET 4.5 to implement some service methods in WCF. Example service:

Contract:

[ServiceContract(Namespace = \"http:/         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 23:11

    Expanding on Mr. Cleary's #1 option, the following code can be placed in the constructor of the WCF service to store and retrieve the OperationContext in the logical call context:

    if (CallContext.LogicalGetData("WcfOperationContext") == null)
    {
         CallContext.LogicalSetData("WcfOperationContext", OperationContext.Current);
    }
    else if (OperationContext.Current == null)
    {
         OperationContext.Current = (OperationContext)CallContext.LogicalGetData("WcfOperationContext");
    }
    

    With that, anywhere you are having issues with a null context you can write something like the following:

    var cachedOperationContext = CallContext.LogicalGetData("WcfOperationContext") as OperationContext;
    var user = cachedOperationContext != null ? cachedOperationContext.ServiceSecurityContext.WindowsIdentity.Name : "No User Info Available";
    

    Disclaimer: This is year-old code and I don't remember the reason I needed the else if in the constructor, but it was something to do with async and I know it was needed in my case.

提交回复
热议问题