goseta goseta - 2 months ago 23
C# Question

Processing binary data in Web API from a POST or PUT REST request

I'm currently developing a REST web service using Web API. I have encountered a problem processing binary data (an image) that has been transmitted via a POST request.

From the perspective of the client, I have managed to send binary data using the jQuery Form Plugin. But because I'm very new to .NET (I'm a PHP developer), I'm having difficulty processing this binary data via Web API on the server.

To confirm that the jQuery Form Plugin is sending the image data correctly, I have written a working PHP handler that makes use of the simple

$_FILE
global variable.

Now I am trying to accomplish the same via Web API. Here is an outline of what I have tried. How do I access the binary data that has been sent?

Model:

namespace EDHDelivery.Models
{
public class Oferta
{
public int OfertaID { get; set; }
public string Nombre { get; set; }
public string Imagen { get; set; }
public int ComercioID { get; set; }
}
}


Controller (partial code shown):

public Oferta Add(Oferta item)
{
/*here my item will have the POST body with form values,
automatically serialized by the framework and I think an image binary*/
var n = item.Nombre; //...etc.
}

Answer

In short, you have to send the data as multipart/form-data (which, I'm pretty sure, you are already doing through the plugin you mentioned) and then you have to extract that data using one of Web API MultipartContent providers.

There are plenty of resources explaining how to that: