【问题标题】:request.ContentType = "application/json" gives bad request error on WCF methodrequest.ContentType = "application/json" 在 WCF 方法上给出错误的请求错误
【发布时间】:2013-04-24 17:49:36
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: c# asp.net wcf rest


    【解决方案1】:

    您的服务出现 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"));
    

    希望对你有所帮助。

    【讨论】:

    • 我的要求是将 Json 作为流发送,因为当我将 json 作为字符串发送时,它周围有双引号,该服务的客户端将发送不带双引号的 json。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多