I need to receive a json object together with a byte array in a c# Web API application.
This is how I am sending the data:
public bool SendMedia(string method, Media media)
{
string filePath = Path.GetFullPath(Path.Combine(filesDirectory, media.FileName));
if (!File.Exists(filePath))
{
return false;
}
using (var client = new HttpClient())
using (var content = new MultipartContent() )
{
content.Add(new StringContent(JsonConvert.SerializeObject(media), Encoding.UTF8, "application/json"));
byte[] b = File.ReadAllBytes(filePath);
content.Add(new ByteArrayContent(b, 0, b.Length));
var response = client.PostAsync(new Uri(baseUri, method).ToString(), content).Result;
if (response.IsSuccessStatusCode)
return true;
return false;
}
}
And this is how I am trying to receive it:
// POST: api/Media
[ResponseType(typeof(Media))]
public HttpResponseMessage PostMedia(Media media, byte[] data)
{
int i = data.Length;
HttpResponseMessage response = new HttpResponseMessage();
if (!ModelState.IsValid)
{
response.StatusCode = HttpStatusCode.ExpectationFailed;
return response;
}
if (MediaExists(media.MediaId))
WebApplication1Context.db.Media.Remove(WebApplication1Context.db.Media.Where(p => p.MediaId == media.MediaId).ToArray()[0]);
WebApplication1Context.db.Media.Add(media);
try
{
WebApplication1Context.db.SaveChanges();
}
catch (DbUpdateException)
{
response.StatusCode = HttpStatusCode.InternalServerError;
return response;
throw;
}
response.StatusCode = HttpStatusCode.OK;
return response;
}
I don't know much about developing for web at the moment. Is sending a MultipartContent the right approach?