如何在没有WebRequest的情况下使用WCF服务?

如何在没有WebRequest的情况下使用WCF服务?

问题描述:

我正试图与一个Web服务接口。我发布了一个SOAP Evelolpe,它返回一个SOAP响应。如何在没有WebRequest的情况下使用WCF服务?

我能够发布到服务并获得响应使用Web请求和Response.But我想用WCF来做到这一点。可以请一些身体帮助我实现这一目标。

我的HTTP帖子:

public string HttpPost (string uri, string parameters) 
{ 
    WebRequest webRequest = WebRequest.Create (uri); 
    webRequest.ContentType = "application/soap+xml; charset=utf-8"; 
    webRequest.Method = "POST"; 
    byte[] bytes = Encoding.ASCII.GetBytes (parameters); 
    Stream os = null; 
    try 
    { // send the Post 
     webRequest.ContentLength = bytes.Length; 
     os = webRequest.GetRequestStream(); 
     os.Write (bytes, 0, bytes.Length);   //Send it 
    } 

    try 
    { // get the response 
     WebResponse webResponse = webRequest.GetResponse(); 
     if (webResponse == null) 
     { return null; } 
     StreamReader sr = new StreamReader (webResponse.GetResponseStream()); 
     return sr.ReadToEnd().Trim(); 
    } 
    return null; 
} 
+0

此外,请参阅http://stackoverflow.com/tags/wcf/info – 2010-11-08 20:33:00

基本上,你需要的是:

  • 要么你可以从(通常:(url of your service)?wsdl)一个WSDL的URL
  • 或获取WSDL (和任何支持XSD)文件从服务提供商例如作为一个ZIP或下载

下一页:从Visual Studio中创建一个项目,然后在References在解决方案资源管理器中单击鼠标右键,然后选择从上下文菜单中Add Service Reference

Add Service Reference Context Menu Item

在磁盘路径在对话框中直接键入URL(与?wsdl),或键入您的WSDL/XSD文件的存储。

Add Service Reference Dialog Box

这将WCF服务参考该服务添加到您的项目。你现在应该在Service Reference下有一个条目 - 在你看到的下面,有一些隐藏的文件,其中包含了现在调用该服务所需的所有生成的代码。

基本上,其中一个文件应该被称为(name of your service)Client - 它在您添加服务引用时定义的名称空间中(默认为ServiceReference1)。使用该命名空间,您现在应该可以创建WCF客户端:

using ServiceReference1; // or whatever you called this namespace 

public void CallService() 
{ 
    YourServiceNameClient client = new YourServiceNameClient(); 

    client.YouShouldSeeServiceMethodsHere(); 
} 

有了这个WCF客户端,你应该能够很容易地调用服务方法,并在参数传递(字符串等)的方法,并且还可能从该服务方法获取响应(作为字符串或作为类)。

+0

我希望我有时间找到这是重复的最古老的问题。我会将它添加到标记wiki中。 – 2010-11-08 20:33:44