У меня возникли проблемы с загрузкой изображения в веб-API, который я запускаю. Я могу извлекать данные из веб-API при использовании запросов GET, но у меня возникают проблемы с запросами POST. Мне нужно загрузить изображение BMP в веб-API, а затем отправить обратно строку json.C# webrequest post image to web api
[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();
}
сторона MVC, которая отправляет изображение выглядит следующим образом:
// 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();
По некоторым причинам я всегда получаю 404 WebException
на
WebResponse response = request.GetResponse();
Я проверил, что URL должен быть правильно. Это как я отформатирую URL для сообщения, или я делаю какую-то другую ошибку?
Edit, добавлена WebConfig маршрутизации:
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 }
);
}
Посмотрите [здесь] (http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi) –
Вы» повторно устанавливая содержимое как multipart/form-data, но поток не кодируется как multipart, проверьте это: http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data – Gusman