在我的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