问题
I saw below but it adds overhead of encode and decode strings.
C# - Send byte[] as part of json object using HttpWebRequest
I have a request object like below
[DataContract]
public class MyRequest
{
[DataMember]
public byte[] SampleByteArray { get; set; }
[DataMember]
public string UserId { get; set; }
}
I have below method that returns a byte[]
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;
}
I am creating my request object like below
MyRequest myRequest = new MyRequest();
myRequest.SampleByteArray = SerializeToByteArray(myDTO);
myRequest.UserId = "XXX";
I am making my HttpWebRequest object like below
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();
I am making WCF Rest call like below
string responseData;
using (WebResponse response = request.GetResponse())
{
using (var respStream = response.GetResponseStream())
{
using (var reader = new System.IO.StreamReader(respStream)
{
responseData = reader.ReadToEnd();
}
}
}
I am getting 400 Bad Request exception at
WebResponse response = request.GetResponse()
To test I changed my code like below and now atleast my service code gets hit and I am getting valid nice exception message which shows that my service is working.
MyRequest myRequest = new MyRequest();
myRequest.SampleByteArray = null;
myRequest.UserId = "XXX";
It looks like I am having issue sending byte[] to my service.
Can anyone please tell me how to send a byte[] as a property in a object that is converted into JSON format and calls a WCF Rest endpoint.
Please see below my service briefly.
[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
}
}
来源:https://stackoverflow.com/questions/60714522/c-sharp-send-byte-as-json-to-wcf-rest-endpoint-400-bad-request