1

我所有的 GET 端点都像冠军一样工作,但我正在尝试实现 webinvoke 方法 =“POST”。

我认为我的格式有问题,但我不知道它是什么,有人可以帮忙吗?

[ServiceContract]
interface iFlowRate
{
     [OperationContract]
     [WebInvoke(Method="POST",UriTemplate = "Add?apikey={apikey}",RequestFormat= WebMessageFormat.Xml)]
     string AddFlowRate(string apikey,FlowRate flowrate);
}

当我调试它时,它甚至没有进入这个方法。我正在调用这样的服务。

string postData = "<FlowRate ><wellname>wellname</wellname></FlowRate>";
//Setup the http request.
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentLength = postData.Length;
request.ContentType = "application/xml";
request.KeepAlive = true;

StreamWriter streamwriter = new
StreamWriter(request.GetRequestStream());
streamwriter.Write(postData);
streamwriter.Close();

// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Read the response
StreamReader responsereader = new StreamReader(response.GetResponseStream());
string strResponseData = responsereader.ReadToEnd();

有任何想法吗?顺便说一句,使用 WCF 4.0,非常感谢任何帮助。

4

1 回答 1

1

直到不久前我终于偶然发现了答案,这完全让我丧命。

这是我的发现的来源:WCF Rest 中的 Wrapped BodyStyle

但我会切入好东西。

首先,设置 ServiceContract 的命名空间。

[ServiceContract(Namespace = "http://mytagservice")]

现在,我确信还有另一种方法可以让它工作,但这就是我破解它的方式。将 BodyStyle 设置为 Wrapped。默认的请求格式是 XML,所以如果您不想在此处设置,则无需在此处设置。

 [WebInvoke(Method="POST",UriTemplate = "Add?apikey={apikey}", BodyStyle = WebMessageBodyStyle.Wrapped)]

然后更改您的 xml 以包含包装器和命名空间。请特别注意标签名称,因为它们区分大小写。

string postData = "<AddFlowRate xmlns='http://mytagservice'><flowrate><wellname>wellname</wellname></flowrate></AddFlowRate>";

因为它使用包装的消息类型,所以这个解决方案将适用于尽可能多的参数。

于 2012-02-16T03:16:17.863 回答