我在将图像上传到我正在运行的 Web API 时遇到问题。使用 GET 请求时,我可以从 Web API 检索数据,但在处理 POST 请求时遇到问题。我需要将 BMP 图像上传到 Web API,然后发回 json 字符串。
[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();
由于某种原因我总是得到 404WebException
on
WebResponse response = request.GetResponse();
我已经检查过 URL 应该是正确的。是我格式化帖子 URL 的方式还是我犯了其他错误?
编辑,添加 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 }
);
}