【问题标题】:Passing XML string in the body of WCF REST service using WebInvoke使用 WebInvoke 在 WCF REST 服务的正文中传递 XML 字符串
【发布时间】:2011-06-06 14:00:17
【问题描述】:

我是 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);
}

// 实现代码

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();

有人能指出其中的问题吗?

【问题讨论】:

  • 如果你使用XElement而不是字符串作为参数,它会改变吗?还要设置请求的Content-Length
  • 感谢您的回复。我尝试使用 XElement。不走运!!

标签: xml wcf rest post webinvoke


【解决方案1】:

更改您的操作合同以使用 XElement 和 Bare 的 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>";

【讨论】:

    【解决方案2】:

    你仍然需要创建一个类:

    public class Test
    {
    
        public string xmlstring{ get; set; }
    
    }
    

    您也可以使用 fiddler 来检查序列化的 XML 是否可以作为参数传递。

    【讨论】:

      【解决方案3】:

      我认为问题在于您将BodyStyle 设置为WrappedRequest,这将要求将传入的XML 包装在定义服务合同的任何命名空间中的&lt;GetXml&gt; 元素中。如果您将BodyStyleBare 并按照 @Ladislav Mmka 在评论中建议的那样使用 XElement,你应该好好去。

      【讨论】:

        【解决方案4】:

        您需要使用适当的 Microsoft XML 序列化命名空间将 XML 字符串包装在 &lt;string/&gt; 标记中。这个问题之前已经在 SO 上回答过,但是我现在找不到。

        【讨论】:

          猜你喜欢
          • 2012-04-17
          • 2011-03-31
          • 2011-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多