繁体   English   中英

获取 System.NullReferenceException:“对象引用未设置为 object 的实例。” 调用服务时

[英]getting System.NullReferenceException: 'Object reference not set to an instance of an object.' when calling a service

我正在使用 .net 内核并使用了 WCF 服务。 当我通过 header 中的 Api 键并调用服务时,它会引发 NullReferenceException 错误。

下面是我用来调用服务的 function

 public async void CallService(string reqdata, string partner) { BasicHttpBinding basicHttpBinding = null; EndpointAddress endpointAddress = null; ChannelFactory<IRequestChannel> factory = null; QuoteEngineService.MarketingSoftwareClient service = new QuoteEngineService.MarketingSoftwareClient(); try { basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; endpointAddress = new EndpointAddress(new Uri("https://Service-engine-dev.110apps.net/Package/TempSoftware.svc?wsdl")); factory = new ChannelFactory<IRequestChannel>(basicHttpBinding, endpointAddress); IRequestChannel channel = factory.CreateChannel(); HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty(); string apikey = "OAvHGAAatytiZno"; httpRequestMessage.Headers.Add("apikey", apikey); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestMessage; service.OpenAsync(); var result2 = await service.PRequestAsync(reqedata, partner); var data = result2; } catch(Exception e) { throw; } finally { if (service.State==System.ServiceModel.CommunicationState.Opened) { service.CloseAsync(); } } } }

我收到错误

 OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestMessage;

空引用异常

错误

如果直接创建服务类型的实例,然后在其上调用方法,则没有 OperationContext。以下示例显示如何使用 OperationContextScope 在客户端应用程序中创建新上下文:

public class Client {
    public void run()
    {
        ServiceReference1.Service1Client service1Client = new Service1Client(new InstanceContext(this));
        using (OperationContextScope scope = new OperationContextScope(service1Client.InnerChannel)) {
            HttpRequestMessageProperty http = new HttpRequestMessageProperty();
            string apikey = "OAvHGAAatytiZno";
            http.Headers.Add("apikey", apikey);
            OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = http;
            ServiceReference1.Result result = service1Client.GetUserData("Test");
        } 
    }
}
class Program

{
    static void Main(string[] args)
    {
        Client client = new Client();
        client.run();
    }
}

这是参考链接:

https://docs.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontext.-ctor?view=dotnet-plat-ext-3.1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM