csharp-web service

目前发现使用 .net core 会有问题。暂时先使用 .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);
}

动态调用 WebService 服务

通常我们在程序中需要调用 WebService 时,都是通过“添加Web引用”,让VS.NET环境来为我们生成服务代理,然后调用对应的Web服务。
在 URL 不确定的情况下,就不适用了。需要动态调用WebService的能力。比如我们可以把Web服务的URL保存在配置文件中,这样,当服务URL改变时,只需要修改配置文件就可以了。

WebService在传输过程中是通过WSDL来进行描述的。因此,我们需要获取WebService的WSDL描述,并通过该描述来动态生成程序集。然后通过反射来获取新生成的程序集,并调用其方法!