0

我使用WCF REST 服务模板 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。但如果它使内容类型简单,它可以工作,但我想传递存储在 json.txt 中的 json。请建议我怎么做?

谢谢。

4

1 回答 1

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"));

希望这可以帮助你。

于 2013-04-25T06:11:20.137 回答