我本来就问我是试着写,然后发现ASP.net网络API是更适合我的需要,由于对这里的一些反馈一个WCF Web服务的问题。C#的Web API REST服务POST
我现在已经找到了一个很好的教程,告诉我如何使用Web API,它工作得很好几乎开箱创建一个简单的REST服务。
我的问题
我有我的REST服务服务器POST方法:
// POST api/values/5
public string Post([FromBody]string value)
{
return "Putting value: " + value;
}
我可以张贴到此使用海报,也是我的C#的客户端代码。
但是我不明白的位为我为什么要在前面加上一个“=”号的POST数据,这样记载:“=这是我的数据,实际上是一个JSON字符串”;而不仅仅是发送:“这是我的数据,它实际上是一个JSON字符串”;
,讨论到REST服务我的C#的客户如下记载:
public string SendPOSTRequest(string sFunction, string sData)
{
string sResponse = string.Empty;
// Create the request string using the data provided
Uri uriRequest = GetFormRequest(m_sWebServiceURL, sFunction, string.Empty);
// Data to post
string sPostData = "=" + sData;
// The Http Request obj
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriRequest);
request.Method = m_VERB_POST;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(sPostData);
request.ContentLength = byteArray.Length;
request.ContentType = m_APPLICATION_FORM_URLENCODED;
try
{
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
sResponse = reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
//Log exception
}
return sResponse;
}
private static Uri GetFormRequest(string sURL, string sFunction, string sParam)
{
StringBuilder sbRequest = new StringBuilder();
sbRequest.Append(sURL);
if ((!sURL.EndsWith("/") &&
(!string.IsNullOrEmpty(sFunction))))
{
sbRequest.Append("/");
}
sbRequest.Append(sFunction);
if ((!sFunction.EndsWith("/") &&
(!string.IsNullOrEmpty(sParam))))
{
sbRequest.Append("/");
}
sbRequest.Append(sParam);
return new Uri(sbRequest.ToString());
}
是任何人能解释为什么我要在前面加上“=”号在上面的代码(string sPostData = "=" + sData;
)?
非常感谢提前!
Whay你不使用restsharp这样的东西吗? http://restsharp.org/ –
@KosalaW http://i.imgur.com/ybWKjSM.png:D – DSF
嗨Kosala W,谢谢你。说实话,我没有看这个,但也许我应该有。我的工作是编写与最终由第三方编写的服务器代码接口的客户端代码。我只需要提供API的测试工具和指南。 考虑到这一点,你是否对上述内容有任何反馈意见,因为在POST数据前加上'='符号似乎是错误的,但如果必须,我会我只想多了解一点? 感谢您使用m_APPLICATION_FORM_URLENCODED – Yos