WCF客户端:传递XML字符串中使用WebInvoke

问题描述:

的,用于显示的方法是工作在浏览器即http://localhost:2617/UserService.svc/testWCF客户端:传递XML字符串中使用WebInvoke

out参数当我添加一个参数,我不能浏览它也是WCF REST服务。

我有以下合同。

[ServiceContract] 
public interface IUserService 
{ 
    [OperationContract] 
    [WebInvoke(Method="PUT",UriTemplate = "/tes/{name}", 
    BodyStyle=WebMessageBodyStyle.WrappedRequest)] 
    string Display(string name); 
} 

public string Display(string name) 
{ 
     return "Hello, your test data is ready"+name; 
} 

我尝试使用下面的代码

  string url = "http://localhost:2617/UserService.svc/test"; //newuser 
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 
     string xmlDoc1 = "<Display xmlns=\"\"><name>shiva</name></Display>"; 
     req.Method = "POST"; 
     req.ContentType = "application/xml"; 
     byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1); 
     req.GetRequestStream().Write(bytes, 0, bytes.Length); 

     HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 
     Stream responseStream = response.GetResponseStream(); 
     var streamReader = new StreamReader(responseStream); 

     var soapResonseXmlDocument = new XmlDocument(); 
     soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd()); 

叫我无法得到输出that.please帮我在这。

+1

你在客户端的方法是“POST”,但在服务器端你有Method =“PUT” - 我以为他们必须是相同的 - 尝试将服务器更改为POST也许? – kmp 2012-04-04 07:20:29

+0

我改变它POST也...我尝试了不同的方式,但它不工作.. – 2012-04-04 11:46:26

+1

你还没有声明一个命名空间,所以命名空间将是http://tempuri.org - 而不是空白。 – Chris 2012-04-05 07:30:11

有几件事情在代码中不太正确。

客户

在你需要指定命名空间是tempuri,因为你还没有宣布明确的一个,所以你的客户端代码将需要此客户端:

string url = "http://localhost:2617/UserService.svc/test"; //newuser 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); 
string xmlDoc1 = "<Display xmlns=\"http://tempuri.org/\"><name>shiva</name></Display>"; 
req.Method = "POST"; 
req.ContentType = "application/xml"; 
byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1); 
req.GetRequestStream().Write(bytes, 0, bytes.Length); 

HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 
Stream responseStream = response.GetResponseStream(); 
var streamReader = new StreamReader(responseStream); 

var soapResonseXmlDocument = new XmlDocument(); 
soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd()); 

服务

在服务UriTemplate是不完全正确的 - 你指定/tes/{name}所以这将是预期g类似于http://localhost:2617/UserService.svc/tes/shiva的URL,但是您想要将XML数据发布到正文中,因此您应该将其更改为UriTemplate = "/test"(我假设您的意思是测试,而不是您的问题中的测试)。

此外,如果您想要向其发送数据(客户端需要匹配服务,并且我假设您在客户端上拥有的是您想要的),则该方法应该是POST。

所以,总而言之,你的IUserService应该是这样的:

[ServiceContract] 
public interface IUserService 
{   
    [OperationContract] 
    [WebInvoke(Method = "POST", 
       UriTemplate = "/test", 
       BodyStyle = WebMessageBodyStyle.WrappedRequest)] 
    string Display(string name); 
} 

你仍然需要创建一个类

public class Test 
{ 

    public string name { get; set; } 

} 

您也可以使用Fiddler检查{名称:999}可以作为参数传递。