是否可以在不添加服务引用的情况下访问WCF服务?

我需要访问Wcf服务方法而不添加服务引用?如何做到这一点?

第1步:我创建一个WCF服务。
第2步:向我的应用程序添加服务引用。
第3步:访问应用程序中的WCF服务方法。

像这样,

ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client(); protected void Button1_Click(object sender, EventArgs e) { UserDetails userInfo = new UserDetails(); userInfo.UserName = TextBoxUserName.Text; userInfo.Password = TextBoxPassword.Text; userInfo.Country = TextBoxCountry.Text; userInfo.Email = TextBoxEmail.Text; string result = obj.InsertUserDetails(userInfo); LabelMessage.Text = result; } 

您可以使用如下。 只需确保添加服务合同参考。

 BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress("http://localhost:4684/Service1.svc"); ChannelFactory factory = new ChannelFactory(binding, address); ServiceContract channel = factory.CreateChannel(); string resturnmessage = channel.YourMethod("test"); 

从这里你可以得到充分的锻炼。

是的,可以在不添加服务引用的情况下调用WCF服务。

作为第一步,我假设您将服务联系人界面作为单独的类库。

步骤2:创建WCF服务并在IIS中托管它

步骤3:在客户端应用程序中引用您的服务合同库,然后按照此代码操作

 ChannelFactory factory = new ChannelFactory("EndpointNameOfYourService"); factory.Endpoint.Address = new EndpointAddress("http://example.com/service"); IYourServiceContract client = factory.CreateChannel(); var result = client.YourMethodtoInvoke(serviceArguments); 

希望这可以帮助

用这种方式冒着降价的暴徒,但……

如果您没有添加引用的原因是您需要在运行时选择URL,您仍然可以添加引用,然后在需要时更改它:

 MyProxy.Endpoint.Address = new EndpointAddress(MyUri); 

(或者在实例化时在构造函数中执行相同的操作)。

我没有评论“Thilina H”的答案,但你可以使用代码

 ServiceContract channel = factory.CreateChannel(); 

只有你写道:

 var factory = new ChannelFactory(binding, address); 

代替

 ChannelFactoryfactory = new ChannelFactory(binding, address); 

在约翰这样做时:“步骤2:向我的应用程序添加服务引用。” Visual Studio将端点和默认绑定添加到其应用程序的app.config文件中。 他不需要指定URL。 只要服务已经实现了所需的合同,John的代码就可以正常工作。