我有此操作合同
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/post/address/")]
ADE.Address GetPostAddress(PostContract DataContract);
这是DataContract
[DataContract]
public class PostContract
{
[DataMember]
public string k { get; set; }
[DataMember]
public string source { get; set; }
[DataMember]
public int isUrl { get; set; }
[DataMember]
public string ISO2Code { get; set; }
}
我尝试从控制台应用程序使用
执行此操作using (var client = new WebClient())
{
var data = new NameValueCollection();
data["k"] = "bla bla bla";
data["source"] = "test text";
data["isUrl"] = "0";
data["ISO2Code"] = "be";
var response = client.UploadValues("http://localhost:83/Ade.svc/post/address/", data);
var responseString = Encoding.Default.GetString(response);
}
我一直收到400错误回复。我使用GET
提供相同的服务,并且工作正常,有时source
超过2000个字符,因此,我必须使用POST
。
我错过了什么明显的东西?
答案 0 :(得分:1)
错误的请求响应是因为内容类型错误。必须从Webclient
切换到httpWebRequest
然后,我可以将ContentType
设置为"application/json"
,这是必需的。我无法使用Content-Type
更改标题Webclient
。
以下代码有效:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:83/Ade.svc/post/address");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"k\":\"key\"," +
"{\"source\":\"test test\"," +
"{\"isUrl\":\"0\"," +
"\"ISO2Code\":\"be\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
<强>更新强>
为了避免在字符串中使用无效字符的错误请求,请使用Json创建自定义类和SerializeObject
。
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
//
// Create new reques object
//
RequestObject rObj = new RequestObject();
rObj.k = ConfigurationManager.AppSettings["restkey"].ToString();
rObj.source = row["SearchText"].ToString();
rObj.isUrl = "0";
rObj.ISO2Code = "be";
streamWriter.Write(JsonConvert.SerializeObject(rObj));
streamWriter.Flush();
streamWriter.Close();
}
答案 1 :(得分:-1)
也许试试这个:
[Serializable]
[DataContract(Name = "PostContract")]
public class PostContract
{
[DataMember(Name = "k")]
public string k { get; set; }
[DataMember(Name = "source")]
public string source { get; set; }
[DataMember(Name = "isUrl")]
public int isUrl { get; set; }
[DataMember(Name = "ISO2Code")]
public string ISO2Code { get; set; }
}