我需要使用带有4个字符串参数的POST方法创建REST服务
我将其定义如下:
[WebInvoke(UriTemplate = "/", Method = "POST", BodyStyle= WebMessageBodyStyle.WrappedRequest)]
public Stream ProcessPost(string p1, string p2, string p3, string p4)
{
return Execute(p1, p2, p3, p4);
}
我想用代码调用它,如下所示:
string result = null;
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string paramz = string.Format("p1={0}&p2={1}&p3={2}&p4={3}",
HttpUtility.UrlEncode("str1"),
HttpUtility.UrlEncode("str2"),
HttpUtility.UrlEncode("str3"),
HttpUtility.UrlEncode("str4")
);
// Encode the parameters as form data:
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz);
req.ContentLength = postData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
// Pick up the response:
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
但是,客户端代码返回代码400:错误请求
我做错了什么?
谢谢
答案 0 :(得分:1)
我会说不支持form-urleconded格式。 WebInvoke属性的RequestFormat属性是WebMessageFormat枚举类型,它只将JSON和XML定义为有效格式。
http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webmessageformat.aspx
答案 1 :(得分:1)
我会说UriTemplate
中的参数如下所示
[OperationContract]
[WebInvoke(UriTemplate = "{p1}/{p2}/{p3}/{p4}", Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string ProcessPost(string p1, string p2, string p3, string p4);
并使用以下代码调用
string result = null;
string uri = "http://localhost:8000/ServiceName.svc/1/2/3/4";
HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
req.KeepAlive = false;
req.Method = "POST";
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
result = reader.ReadToEnd();
}
对我来说很好。希望这种方法很有用。