对WCF服务使用POST时出现问题
本文关键字:问题 POST WCF 服务 | 更新日期: 2023-09-27 18:24:40
我有这个操作合同
[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
。
有什么明显我遗漏的吗?
错误的请求响应是因为内容类型错误。必须从Webclient
切换到httpWebRequest
然后我可以将ContentType
设置为需要的"application/json"
。我无法使用Webclient
更改标头Content-Type
。
以下代码工作:
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();
}
也许可以试试这个:
[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; }
}