Well I have a small test applicationn a .NET Web API and a library for both sharing some classes.
My goal is to pass a object via POST request to the api.
This is how my program looks like:
var metadata = new Metadata(); // Metadata is a empty class in my library
try
{
var postData = ByteConverter.ObjectToByteArray(metadata); // ByteConverter.ObjectToByteArray is method in my library to convert objects to a byte array
var request =
(HttpWebRequest)WebRequest.Create("http://localhost:65160/test");
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postData.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, postData.Length);
}
await request.GetResponseAsync();
}
catch (Exception ex)
{
// ignored
}
And this is how the POST method of my api looks like:
[HttpPost]
public HttpResponseMessage Test([FromBody] Metadata metadata)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
The method of my api is called but the metadata param is always null. What do I have to change to make it work?
Edit:
As requested:
public static byte[] ObjectToByteArray(object obj)
{
if(obj == null)
throw new ArgumentNullException($"The parameter {nameof(obj)} can't be null");
try
{
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
catch (SerializationException)
{
throw;
}
catch
{
return new byte[0];
}
}
ByteConverter.ObjectToByteArraydoes: I hope it serializes your object into JSON and only then returns the resulting text as a byte array. Am I right? Can you post the implementation?metadatato JSON string representation of the object then convert it to bytes. Are you able to useHttpClientor are you restricted to usingWebClient?