I'm having trouble uploading an image to a Web API that i'm running. I can retrieve data from the Web API when using GET requests, but I'm having trouble with POST requests. I need to upload an BMP image to the Web API and then send back a json string.
[HttpPost]
public IHttpActionResult TestByte()
{
Log("TestByte function entered");
//test to see if i get anything, not sure how to do this
byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
byte[] test = Convert.FromBase64String(payload);
if(test == null || test.Length <= 0)
{
Log("No Payload");
return NotFound();
}
if (data == null || data.Length <= 0)
{
Log("No payload");
return NotFound();
}
Log("Payload received");
return Ok();
}
The MVC side that sends the image looks like this:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = GetImageData(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, content, barcodeUri));
string base64String = Convert.ToBase64String(byteArray);
byte[] dataArray = Encoding.Default.GetBytes(base64String);
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data";
// Set the ContentLength property of the WebRequest.
request.ContentLength = dataArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(dataArray, 0, dataArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
For some reason I always get an 404 WebException
on
WebResponse response = request.GetResponse();
I have checked that the URL should be right. Is it how I format the URL for post or am I making some other mistake?
Edit, added webconfig routing:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}