动态创建的Web引用
本文关键字:引用 Web 创建 动态 | 更新日期: 2023-09-27 18:09:32
我正在开发android应用程序在Xamarin android在c#。有什么方法可以动态更改SOAP web服务的URL吗?我想在某种配置文件中存储url,但我不知道如何做到这一点。
如果我说错了请指正
但是xamarin - soap webservice类的第二个构造函数有一个URL属性。
这是我的webservice的一个例子:
public partial class Service : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public Service()
{
this.Url = "http://xxx/service.asmx";
}
public Service(string url)
{
this.Url = url;
}
}
你已经在xamarin中添加了webreference,然后使用你的webservice - instance。
只需调用第二个构造函数,并给它们一个其他url作为源。
您可以使用Channelfactory手动创建所需的连接,它可以根据需要进行更改。你需要适当的网络连接。配置文件。
你可以这样设置。
在你的web.config.
<appSettings>
<add key="Identity" value="machineidentity" />
<add key="Binding" value="WSHttpBinding_IService" />
<add key="Endpoint" value="http://Devservice/Service.svc" />
<add key="Identity2" value="localmachine" />
<add key="Binding2" value="WSHttpBinding_IService" />
<add key="Endpoint2" value="http://Devservice/Service.svc" />
<add key="devIdentity" value="localmachine" />
<add key="devBinding" value="WSHttpBinding_IService" />
<add key="devEndpoint" value="http://Devservice/Service.svc" />
</appSettings>
c# code
保存web.config
中的值的配置类public static Dictionary<int, Connections> EndpointConnections = new Dictionary<int, Connections>
{
{1, new Connections(){Identity = ConfigurationManager.AppSettings["Identity"],Binding = ConfigurationManager.AppSettings["Binding"], Endpoint = ConfigurationManager.AppSettings["Endpoint"]}},
{2, new Connections(){Identity = ConfigurationManager.AppSettings["Identity2"],Binding = ConfigurationManager.AppSettings["Binding2"], Endpoint = ConfigurationManager.AppSettings["Endpoint2"]}},
{3, new Connections(){Identity = ConfigurationManager.AppSettings["devIdentity"],Binding = ConfigurationManager.AppSettings["devBinding"], Endpoint = ConfigurationManager.AppSettings["devEndpoint"]}},
};
现在是创建端点的静态类
private ChannelFactory<IService> SetChannelFactory(int configInput)
{
var identity = EndpointIdentity.CreateDnsIdentity(Configuration.EndpointConnections[configInput].Identity);
var myBinding = new WSHttpBinding(Configuration.EndpointConnections[configInput].Binding);
var myuri = new Uri(Configuration.EndpointConnections[configInput].Endpoint);
var myEndpoint = new EndpointAddress(myuri, identity);
return new ChannelFactory<IService>(myBinding, myEndpoint);
}
现在调用和使用端点
public async Task<Result> SomeAction(int selection)
{
IService client = null;
Result result = null;
Response response = null;
using (var myChannelFactory = SetChannelFactory(selection))
{
try
{
client = myChannelFactory.CreateChannel();
response = await client.TheServiceFunction().ConfigureAwait(false);
((ICommunicationObject)client).Close();
}
catch
{
if (client != null)
{
((ICommunicationObject)client).Abort();
return new result ( failure = true);
}
}
}
if (response != null)
{
//Whatever you want to do with the response here
return new result ( failure = false);
}
}