2011-06-06 75 views
5

我是WCF,REST等的新手。我试图编写服务和客户端。 我想将xml作为字符串传递给服务并获得一些响应。使用WebInvoke在WCF REST服务体内传递XML字符串

我想通过身体的xml到POST方法,但是当我运行我的客户端时,它只是挂起。

当我将服务更改为接受参数作为uri的一部分时,它正常工作。 (当我将UriTemplate从“getString”更改为“getString/{xmlString}”并传递字符串参数时)。

我在粘贴下面的代码。

服务

[ServiceContract] 
public interface IXMLService 
{ 
    [WebInvoke(Method = "POST", UriTemplate = "getString", BodyStyle=WebMessageBodyStyle.WrappedRequest, 
    RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)] 

    [OperationContract] 
    string GetXml(string xmlstring); 
} 

// Implementaion代码

public class XMLService : IXMLService 
{ 
    public string GetXml(string xmlstring) 
    { 
     return "got 1"; 
    } 
}  

客户

string xmlDoc1="<Name>";   
xmlDoc1 = "<FirstName>First</FirstName>"; 
xmlDoc1 += "<LastName>Last</LastName>"; 
xmlDoc1 += "</Name>"; 

HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(@"http://localhost:3518/XMLService/XMLService.svc/getstring"); 
request1.Method = "POST"; 
request1.ContentType = "application/xml"; 
byte[] bytes = Encoding.UTF8.GetBytes(xmlDoc1);   
request1.GetRequestStream().Write(bytes, 0, bytes.Length); 

Stream resp = ((HttpWebResponse)request1.GetResponse()).GetResponseStream(); 
StreamReader rdr = new StreamReader(resp); 
string response = rdr.ReadToEnd(); 

可能有人请指出什么是错的呢?

+0

如果您使用'XElement'而不是字符串作为参数,它会改变吗?还要设置请求的“Content-Length”。 – 2011-06-06 14:05:36

+0

谢谢你的回复。 我试过使用XElement。没有运气!! – sumi 2011-06-06 14:26:23

回答

8

更改为使用的XElement和裸

的BodyStyle你的经营合同
[WebInvoke(Method = "POST", 
    UriTemplate = "getString", 
    BodyStyle = WebMessageBodyStyle.Bare, 
    RequestFormat = WebMessageFormat.Xml, 
    ResponseFormat = WebMessageFormat.Xml)] 
[OperationContract] 
string GetXml(XElement xmlstring); 

此外,我怀疑你的客户端代码应该包含(注意:第一+ =):

string xmlDoc1="<Name>"; 
xmlDoc1 += "<FirstName>First</FirstName>"; 
xmlDoc1 += "<LastName>Last</LastName>"; 
xmlDoc1 += "</Name>"; 
0

我相信问题是,你设置BodyStyleWrappedRequest这就需要你输入的XML被包裹在任何命名空间为您服务合同中定义的<GetXml>元素。如果设置BodyStyleBare和使用XElement作为@Ladislav Mmka在评论中建议你应该很好去。

0

您需要用合适的Microsoft XML序列化命名空间将您的XML字符串包装在<string/>标记中。这个问题在此之前已经得到解答,但目前我找不到它。

1

你仍然需要创建一个类:

public class Test 
{ 

    public string xmlstring{ get; set; } 

} 

您还可以使用fiddler来检查序列化的XM L可以作为参数传递。