使用WebInvoke在WCF REST服务的主体中传递XML字符串 [英] Passing XML string in the body of WCF REST service using WebInvoke

查看:115
本文介绍了使用WebInvoke在WCF REST服务的主体中传递XML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WCF,REST等的新手.我正在尝试编写服务和客户端. 我想将xml作为字符串传递给服务,并获得一些响应.

I'm a newbie to WCF, REST etc. I'm trying to write a service and a client. I want to pass xml as string to the service and get some response back.

我正在尝试将主体中的xml传递给POST方法,但是当我运行客户端时,它会挂起.

I am trying to pass the xml in the body to the POST method, but when I run my client, it just hangs.

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

It works fine when I change the service to accept the parameter as a part of the uri. (when I change UriTemplate from "getString" to "getString/{xmlString}" and pass a string parameter).

我要粘贴下面的代码.

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

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

Could somebody please point out what's wrong in it?

推荐答案

更改您的操作合同以使用XElement和Bare的BodyStyle

Change your operation contract to use an XElement and the BodyStyle of Bare

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

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

Additionally I suspect you client code should contain (note the first +=):

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

这篇关于使用WebInvoke在WCF REST服务的主体中传递XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆