以编程方式确定c#中Web服务的端点
本文关键字:Web 服务 端点 编程 方式确 | 更新日期: 2023-09-27 18:08:46
我正在为我制作的windows服务构建一个插件(它是c#,使用插件来完成某些功能)。这个新插件将使用Web服务来调用Web服务并获取一些信息。
不幸的是,我的DEV、QC和PRODUCTION环境的web-service URL是不同的。我想使端点URL是可配置的(插件将查看数据库并获取URL)。
我如何,确切地,在我的代码中设置一个web服务调用者,使它可以使用一个动态端点?
我可以添加一个服务,并指向DEV中现有的一个-这建立了我的代理类-但我怎么能使它不是"硬锁定"的URL -所以插件可以在任何环境下工作(基于数据库中的URL它拉出来)?可以这么说,我希望能够在代码中动态地改变这一点。
基本上你可以调用这个来创建你的WCF服务客户端:
MyClient = new MyWCFClient(new BasicHttpBinding("CustomBinding"), new EndpointAddress(GetEndpointFromDatabase()));
其中GetEndpointFromDatabase()
返回一个string
——端点
我制作了一个在LINQPad中运行的端到端示例。这适用于完全自托管的场景,并支持探索各种绑定等(针对客户端和服务器)。希望这不是过分的,并发布了整个示例,以防您以后发现任何其他方面有帮助。
void Main()
{
MainService();
}
// Client
void MainClient()
{
ChannelFactory cf = new ChannelFactory(new WebHttpBinding(), "http://localhost:8000");
cf.Endpoint.Behaviors.Add(new WebHttpBehavior());
IService channel = cf.CreateChannel();
Console.WriteLine(channel.GetMessage("Get"));
Console.WriteLine(channel.PostMessage("Post"));
Console.Read();
}
// Service
void MainService()
{
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8080"));
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService),new WebHttpBinding(), "");
ServiceDebugBehavior stp = host.Description.Behaviors.Find();
stp.HttpHelpPageEnabled = false;
stp.IncludeExceptionDetailInFaults = true;
host.Open();
Console.WriteLine("Service is up and running");
Console.ReadLine();
host.Close();
}
// IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method="GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetMessage(string inputMessage);
[OperationContract]
[WebInvoke(Method="POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string PostMessage(string inputMessage);
[OperationContract]
[WebInvoke(Method="POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
System.IO.Stream PostJson(System.IO.Stream json);
}
// Service.cs
public class Service : IService
{
public string GetMessage(string inputMessage){
Console.WriteLine(inputMessage);
return "Calling Get for you " + inputMessage;
}
public string PostMessage(string inputMessage){
Console.WriteLine(inputMessage);
return "Calling Post for you " + inputMessage;
}
public System.IO.Stream PostJson (System.IO.Stream json) {
Console.WriteLine(new System.IO.StreamReader(json).ReadToEnd());
return json;
}
}
不能把URI放在.config文件中吗?你可以在调试或发布时通过在.debug.config和.release.config中设置不同的URI来改变URI。
直接设置url点
TheWebservice.Url = TheUrlFromTheDatabase;