比方說,我指定了以下WCF REST服務地址「http://localhost/MyRESTService/MyRESTService.svc」在WCF REST服務中通過POST發送參數的正確URI是什麼?
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/receive")]
string Receive(string text);
現在我可以調用提琴手我的REST的服務使用的地址「http://localhost/MyRESTService/MyRESTService.svc/receive」和它的作品(我會得到一個返回值)。
但是如果我想將參數發送到我的REST服務呢?我應該改變我的接口定義看起來像這樣:
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/receive/{text}")]
string Receive(string text);
現在,如果我將使用的地址「http://localhost/MyRESTService/MyRESTService.svc/receive/mytext」它的工作原理(發送參數「mytext的內容」,我會得到調用REST服務的提琴手一個返回值)。那麼這是通過POST發送參數的正確URI嗎?
讓我感到困惑的是,當我發送參數時,我不知道如何在代碼中完全使用此URI。我有以下代碼幾乎完成發送POST數據到WCF REST服務,但我堅持如何將參數考慮到URI。
Dictionary<string, string> postDataDictionary = new Dictionary<string, string>();
postDataDictionary.Add("text", "mytext");
string postData = "";
foreach (KeyValuePair<string, string> kvp in postDataDictionary)
{
postData += string.Format("{0}={1}&", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value));
}
postData = postData.Remove(postData.Length - 1);
Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
byte[] postArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(postArray, 0, postArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
如果我要發送的參數(如 「mytext的」)在通過POST代碼應URI代碼是要麼
這
Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive");
或本(這工作,但它沒有任何意義,因爲參數應該以其他方式添加,而不是直接添加到URI地址)
Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive/mytext");
我是很高興如果你能幫助我,WCF REST服務不會如此困難。
我得到這個(「400」)err味精,但只有從運行較舊(精簡版)的.NET的手持設備調用時。就我而言,至少,我不認爲需要對服務器進行更改,因爲我的代碼可以從「當代」客戶端項目(在VS 2013中創建的Winforms應用程序)中正常工作, – 2014-08-29 23:39:19