c# - 获取 System.NullReferenceException:“对象引用未设置为对象的实例。” 调用服务时
问题描述
我正在使用 .net 核心并使用了 WCF 服务。当我在标头中传递 Api 键并调用服务时,它会引发 NullReferenceException 错误。
下面是我用来调用服务的函数
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();
}
}
这是参考链接:
推荐阅读
- javascript - Ajax Vanilla JS - ajax 异步继续而不等待 readyState 4,状态 200
- javascript - 如何在 vue.js 中格式化以千、百万或十亿为单位的数字?
- c - 如何检查图中的循环?
- javascript - Node.js,通过对象数组进行映射,并将特定值放入新数组中
- kubernetes - 如何将一个持久卷声明的数据与另一个隔离
- mongodb - 使用来自不同集合的字段的 MongoDB 查询
- python - 按多个元素按升序和降序排列元组列表
- sql - 基于 DATE_TRUNC 的 SQL 查询中的项目计数总和
- android - 如何从firebase预构建登录ui注销
- bash - Bash:运行命令的最有效方式(命令“可能”或“可能不”存在