【发布时间】:2011-03-23 06:55:16
【问题描述】:
假设我在地址“http://localhost/MyRESTService/MyRESTService.svc”指定了以下 WCF REST 服务
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/receive")]
string Receive(string text);
现在我可以使用地址“http://localhost/MyRESTService/MyRESTService.svc/receive”在 Fiddler 中调用我的 REST 服务并且它可以工作(我会得到一个返回值)。
但是如果我想向我的 REST 服务发送参数怎么办?我应该将我的接口定义更改为如下所示:
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/receive/{text}")]
string Receive(string text);
现在,如果我使用地址“http://localhost/MyRESTService/MyRESTService.svc/receive/mytext”在 Fiddler 中调用 REST 服务,它可以工作(它发送参数“mytext”,我会得到一个返回值)。那么这是通过 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();
如果我想通过 POST 在代码中发送参数(例如“mytext”),那么 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 服务不会那么困难。
【问题讨论】:
标签: wcf rest parameters uri