使用WebInvoke在WCF REST服务的主体中传递XML字符串

sum*_*umi 5 xml rest wcf post 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);
}
Run Code Online (Sandbox Code Playgroud)

//实施代码

public class XMLService : IXMLService
{
    public string GetXml(string xmlstring)
    {
        return "got 1";
    } 
}    
Run Code Online (Sandbox Code Playgroud)

客户

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();
Run Code Online (Sandbox Code Playgroud)

有人可以指出它有什么问题吗?

Mau*_*ice 8

将操作合同更改为使用XElement和Bare的BodyStyle

[WebInvoke(Method = "POST", 
    UriTemplate = "getString", 
    BodyStyle = WebMessageBodyStyle.Bare,
    RequestFormat = WebMessageFormat.Xml, 
    ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
string GetXml(XElement xmlstring);
Run Code Online (Sandbox Code Playgroud)

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

string xmlDoc1="<Name>";
xmlDoc1 += "<FirstName>First</FirstName>";
xmlDoc1 += "<LastName>Last</LastName>";
xmlDoc1 += "</Name>";
Run Code Online (Sandbox Code Playgroud)