【问题标题】:Error while reading body of request message through JSON通过 JSON 读取请求消息正文时出错
【发布时间】:2020-12-31 19:20:42
【问题描述】:

我需要从 WCF REST 服务中的请求正文中读取消息内容,例如 -

服务端代码

string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());

但是无论我尝试什么,我都会在服务端遇到错误:

期待来自命名空间“http://schemas.microsoft.com/2003/10/Serialization/”的元素“base64Binary”。遇到名为“人类”、命名空间“http://numans.hr-”的“元素” xml.org/2007-04-15'。

服务合同定义为:

 //[OperationContract(Name = "LoadMessages", IsOneWay = true)]
    [WebInvoke(Method = "POST",
        UriTemplate = "/LoadMessages",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    [Description("Inbound Message")]
    void LoadMessages();

实现如下:

    public void LoadMessages()
    {
        string content = string.Empty;
        //var request = OperationContext.Current.RequestContext.RequestMessage.GetBody<FileState>();
        string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
 }

客户端代码

我发送的内容是:

string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";

我尝试了许多选项来从客户端发送数据,例如:

var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

也试过这个:

var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

发帖要求:

 HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;

我也尝试在客户端/服务器端进行序列化/反序列化,但这也不起作用。

有人可以建议我可以尝试的代码示例吗?或者指出我做错了什么。

我尝试使用 JSON 数据的更多示例:

 var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented); 
 var details = JObject.Parse(data);

为了清楚起见,粘贴我的客户端函数:

  HttpClient httpClient = new HttpClient(new HttpClientHandler());
  HttpStatusCode statusCode = HttpStatusCode.OK;
  string auditMessage = string.Empty;
  using (httpClient)
  {
     var url = ConfigurationManager.AppSettings["APIURL"];
     try
     {
        string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
                    
         //var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
         //var details = JObject.Parse(data);

         //var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
        var content = new ByteArrayContent(buffer);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
        statusCode = executionResult.StatusCode;
        if (statusCode == HttpStatusCode.Accepted)
        {
          file.Status = "Success";
        }
      }
      catch (Exception ex)
      {
      }
    }

【问题讨论】:

    标签: rest wcf post wcf-rest wcf-rest-contrib


    【解决方案1】:

    这是我的演示:

    这是服务的接口文档:

    这是请求:

    class Program
    {
        
        static void Main(string[] args)
        {
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8012/ServiceModelSamples/service/user");
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-16";
            string Json = "{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}";
            request.ContentLength = Encoding.UTF8.GetByteCount(Json);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(Json);
            myStreamWriter.Close();
    
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
            Stream myResponseStream = response.GetResponseStream();
            //myResponseStream.ResponseSoapContext
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            Console.WriteLine(retString);
            Console.ReadKey();
    
        }
    }
    

    如果问题仍然存在,请随时告诉我。

    更新

    定义测试类:

    [DataContract]
        public class Test { 
        [DataMember]
        public string categoryid { get; set; }
        [DataMember]
        public string fileId { get; set; }
        }
    

    实现如下:

    public void LoadMessages(Test test)
        {
      Test dataObject = OperationContext.Current.RequestContext.RequestMessage.GetBody<Test>(new DataContractJsonSerializer(typeof(Test)));
               Console.WriteLine(dataObject.categoryid);
     }
    

    【讨论】:

    • 我更新了我的问题以获得更多细节,添加了客户端功能。我在阅读服务端请求正文时遇到问题,您的代码似乎正在阅读客户端响应(如果我错了,请纠正我)。你能看到我上面的代码并提出建议吗?
    • 你好,我在SO上发现了一个类似的问题,你可以参考这个链接:stackoverflow.com/questions/33998431/…
    • 我试过这样,它没有用,所以发布了另一个针对我的问题的问题。这就是我在服务中接收内容的方式(取决于我发送的方式 - 有时是 root type="object"){ "categoryid":"e2769919-4b07-42e4-bf18-001a7fce436b", "fileId":"3405" }
    • 您可以尝试先用 Postman 发送请求。
    • 我已经通过 Postman 测试了服务端代码,令人惊讶的是,它可以工作。我正在通过 Postman 发送相同的数据 - { "categoryid": "E2265519-4D237-42E4-BF18-001A7FCE436B", "fileId": "3405" } 。我从这样的服务传递 - string data = "{ \" categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }"; var content = new StringContent(data, Encoding.UTF8, "application/json");所以我不确定我是不是传错了。
    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-25
    • 2022-01-26
    • 2018-11-08
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多