csharp-调用web service

更改服务的 url,只需要更改 App.config 里面的 地址 就可以了

调试的时候使用的地址和生产地址不同。所以调试时添加的地址在 Properties- Settings.settings-Settings.Designer.cs 里面,修改这里可以改默认连接的地址

fwHYUpload.WSHYUpload.LPSWebService hyService = new fwHYUpload.WSHYUpload.LPSWebService();
// 动态修改路径
hyService.Url = App.db.m_config[0].ServicPath;

.net core

添加 web service 服务。
项目上右键-add-connected service-Microsoft WCF Web Service Reference Provider
输入 url 点击 go 在下面配置 namespace 然后 注意是使用同步接口还是异步接口(默认)。

// WSClient is namespace. 
// sendMrlMeasuringData is synchronous method
WSClient.LPSWebServiceClient hyService = new WSClient.LPSWebServiceClient();
var s= hyService.sendMrlMeasuringData("test");

.net framework 项目右键

问题

ServiceReference1.xxxxxx”的终结点配置部分,因为找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分

原因请在解决方案资源管理器界面找到App.config文件打开。查看是否bindings项有多个,确实有多个话,删掉没有使用的binding相关的信息,只保留一个,或者后期手动代码指定选择哪一个。

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WebServiceSoap" />
<binding name="WebServiceSoap1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://10.29.68.32/WebService.asmx" binding="basicHttpBinding"
bindingConfiguration="WebServiceSoap" contract="ServiceReference.WebServiceSoap"
name="WebServiceSoap" />
<endpoint address="http://10.29.68.32/WebService.asmx" binding="basicHttpBinding"
bindingConfiguration="WebServiceSoap1" contract="ServiceReference.WebServiceSoap"
name="WebServiceSoap1" />
</client>
</system.serviceModel>

//所以删掉一个节点既可也可以在页面引用的时候指定bindingConfiguration名字:
ServiceReference.WebServiceSoap web = new WebServiceSoapClient("WebServiceSoap");

服务器无法处理请求。 —> 未将对象引用设置到对象的实例

“默认添加服务引用是通过WCF的方式添加的,这种方式可能会存在问题,添加Web服务的话是按照wsdl协议的;”
“你调用的是一个WebService当然最好是使用Web引用的方式了。毕竟WCF是后来出的,说是兼容WebService,但是总归没有原生态的好。”

添加 service reference 的时候 选择下面的 Advance 按钮 弹出界面中 选择 Add Web Reference. 就可以了
调用时和 wcf 有些不同。

样例

wrUser.wsUser ws = new wrUser.wsUser();
var jsonObj = new JObject { { "UserCode", user }, { "UserPassword", password } };
string strMsg = jsonObj.ToString(Formatting.None);
string strResponse = "";
try
{
strResponse = ws.CheckUser("", jsonObj.ToString(Formatting.None));
}
catch (System.Net.WebException e1)
{
Console.WriteLine("SOAP Exception Message: {0}", e1.Message);
Log.Error("SOAP Exception Message: {0}", e1.Message);
MessageBox.Show($"访问后台接口失败,msg={e1.Message}");
}catch(System.Web.Services.Protocols.SoapException e1)
{
Console.WriteLine("SOAP Exception Message: {0}", e1.Message);
MessageBox.Show($"访问后台接口失败,msg={e1.Message}");
Log.Error("SOAP Exception Message: {0}", e1.Message);
}