请求.ContentType = "application/json"在WCF方法上给出错误请求错误
本文关键字:请求 quot 错误 方法 出错 WCF ContentType application json | 更新日期: 2023-09-27 18:10:56
我使用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,它存储在json。txt。请告诉我怎么做?
谢谢。
您的服务给出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"));