我使用WCF REST Service Template 40(CS)创建了一个WCF服务,方法标题如下所示:
[WebInvoke(UriTemplate = "CTNotification", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public string CTNotification(Stream contents)
以下是我使用它的方式:
string url = ConfigurationManager.AppSettings["serviceUrl"];
string requestUrl = string.Format("{0}CTNotification", url);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "application/json";
//request.ContentType = "text/plain";
request.Timeout = 5000000;
byte[] fileToSend = File.ReadAllBytes(Server.MapPath("~/json.txt"));
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
Label1.Text = "file uploaded successfully";
它给错误400.但如果它使内容类型为plain,它可以工作,但我想传递存储在json.txt中的json。请建议我怎么做?
感谢。
答案 0 :(得分:0)
您的服务出现400错误,因为您传递给服务的数据不是JSON格式。您已使用RequestFormat = WebMessageFormat.Json
修改了操作合同,因此它只接受JSON格式的数据。
您正在使用Stream
数据向服务发出请求,其MIME类型为"text/plain" and "application/octet-stream"
。要将JSON发送到存储在文件中的服务,您需要在服务和客户端下面进行更改:
服务:
[WebInvoke(UriTemplate = "CTNotification", Method = "POST", ResponseFormat =WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public string CTNotification(string contents)
客户端:
string fileToSend = File.ReadAllText(Server.MapPath("~/json.txt"));
希望这可以帮助你。