C#将byte []作为JSON发送到WCF Rest端点。 400错误的请求

时间:2020-03-16 23:35:34

标签: c# arrays json httpwebrequest

我在下面看到了,但是它增加了编码和解码字符串的开销。

C# - Send byte[] as part of json object using HttpWebRequest

我有一个如下的请求对象

[DataContract]
public class MyRequest
{
 [DataMember]
 public byte[] SampleByteArray { get; set; }

 [DataMember]
 public string UserId { get; set; }

}

我有下面的方法返回一个字节[]

public byte[] SerializeToByteArray<T>(T input)
{
  byte[] byteArray = null;
  BinaryFormatter bf = new BinaryFormatter();
  using (MemoryStream ms = new MemoryStream())
  {
    bf.Serialize(ms, input);
    byteArray = ms.ToArray();
  }
  return byteArray;
}

我正在如下创建我的请求对象

MyRequest myRequest = new MyRequest();
myRequest.SampleByteArray = SerializeToByteArray(myDTO);
myRequest.UserId = "XXX";

我正在像下面那样制作HttpWebRequest对象

HttpWebRequest request = WebRequest.CreateHttp(url);
request.ContentType = "application/json";
request.KeepAlive = false;

//100,000 milliseconds (100 seconds) need 10 minutes 
request.Timeout = (int)TimeSpan.FromMinutes(10).TotalMilliseconds;
string stringfydata = Newtonsoft.Json.JsonConvert.SerializeObject(myRequest);
byte[] data = Encoding.UTF8.GetBytes(stringfydata);
request.ContentLength = data.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

我正在像下面那样拨打WCF休息电话

string responseData;
using (WebResponse response = request.GetResponse())
{
   using (var respStream = response.GetResponseStream())
   {
      using (var reader = new System.IO.StreamReader(respStream)
      {
          responseData = reader.ReadToEnd();
      }
   }
}

我在

处收到400错误的请求异常
WebResponse response = request.GetResponse()

为了进行测试,我像下面那样更改了代码,现在至少我的服务代码被命中,并且我收到了有效的异常消息,表明我的服务正在工作。

MyRequest myRequest = new MyRequest();
myRequest.SampleByteArray = null;
myRequest.UserId = "XXX";

似乎我在向我的服务发送byte []时遇到问题。

任何人都可以告诉我如何在转换为JSON格式并调用WCF Rest终结点的对象中发送byte []作为属性。

请在下面简要查看我的服务。

[ServiceContract]
public interface IMyInterface
{
  [Description("My test method")]
  [OperationContract]
  [WebInvoke(
    UriTemplate = "mymethod",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json
   )]
  ServiceResponse GetResponse(MyRequest request);
}

public class MyInterface : IMyInterface
{
 public ServiceResponse GetResponse(MyRequest request)
 {
  .... code goes here
 }
}

0 个答案:

没有答案
相关问题