在我的ASP.NET MVC项目中,我试图从Controller action方法将图像发布到API控制器方法。计划是利用此API将其他客户端用于上传图片。将MultipartFormDataContent从Controller Action方法发布到WebApi Post方法
我能够成功地从Controller Action方法中点击API Post方法,但无法传递图像对象。
这里是我的HomeController.cs
Upload
操作方法
[HttpPost]
public async Task<ActionResult> Upload(FormCollection formCollection)
{
var baseUri = "http://localhost/api/Process";
HttpPostedFileBase file = Request?.Files[0];
if (file == null || (file.ContentLength <= 0) || string.IsNullOrEmpty(file.FileName))
return new EmptyResult();
string fileName = file.FileName;
byte[] fileBytes = new byte[file.ContentLength];
HttpContent stringContent = new StringContent(fileName);
HttpContent fileStreamContent = new StreamContent(file.InputStream);
HttpContent bytesContent = new ByteArrayContent(fileBytes);
using (var formDataContent = new MultipartFormDataContent())
{
formDataContent.Add(stringContent, "fileName", fileName);
formDataContent.Add(fileStreamContent, "inputStream", fileName);
formDataContent.Add(bytesContent, "fileBytes", fileName);
using (var httpClient = new HttpClient())
{
formDataContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(baseUri, formDataContent);
var content = await response.Content.ReadAsStringAsync();
//Handle the response
}
}
return View("Result");
}
在从ApiController
继承我的过程控制,我有以下的邮政法
[HttpPost]
public async Task<string> Post([FromBody]MultipartFormDataContent formDataContent)
{
Task<string> imageContent = Request.Content.ReadAsStringAsync();
string body = imageContent.Result;
ImageResponse imageResponse = null;
//.................
//.................
return someValue
}
这里参数formDataContent
总是空和Request.Content.ReadAsStringAsync()
是空
你尝试'Request.Content.ReadAsMultipartAsync' ? – Jag