【发布时间】:2014-01-16 21:44:35
【问题描述】:
我正在尝试将一个或多个文件 (.doc) 发送到 ASP.NET Web API 2 服务并返回修改后的版本 (.docx)。我能够发送文件并获得响应,但是我在请求中的 HTTPContent 的服务中使用的 HttpContentMultipartExtensions 在客户端中无法用于响应。这是不是开箱即用的东西,可以连接,还是这是对 multipartform 的滥用?
有两个应用程序:MVC 客户端和 Web API 服务:
客户端控制器(从 App_Data 读取示例文件,POST 到 serviceserver/api/mpformdata):
public async Task<ActionResult> PostMpFormData()
{
DirectoryInfo dir = new DirectoryInfo(Server.MapPath(@"~\App_Data"));
var files = dir.GetFiles().ToList();
using (HttpClient client = new HttpClient())
{
HttpResponseMessage result = new HttpResponseMessage();
using (MultipartFormDataContent mpfdc = new MultipartFormDataContent())
{
foreach (var file in files)
{
mpfdc.Add(new StreamContent(file.OpenRead()), "File", file.Name);
}
var requestUri = ConfigurationManager.AppSettings["DocumentConverterUrl"] + "/api/mpformdata";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));
result = client.PostAsync(requestUri, mpfdc).Result;
}
ViewBag.ResultStatusCode = result.StatusCode;
ViewBag.ContentLength = result.Content.Headers.ContentLength;
// Fiddler show that it returns multipartform content, but how do I use it?
// var resultContent = result.Content;
}
return View();
}
Web API 服务控制器:
public class UploadController : ApiController
{
[HttpPost, Route("api/mpformdata")]
public async Task<HttpResponseMessage> PostMpFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
return await UseMultipartFormDataStream();
}
private async Task<HttpResponseMessage> UseMultipartFormDataStream()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
MultipartFormDataContent mpfdc = new MultipartFormDataContent();
try
{
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
var filename = file.Headers.ContentDisposition.FileName;
Trace.WriteLine(filename);
Trace.WriteLine("Server file path: " + file.LocalFileName);
mpfdc.Add(new ByteArrayContent(File.ReadAllBytes(file.LocalFileName)), "File", filename);
}
var response = Request.CreateResponse();
response.Content = mpfdc;
response.StatusCode = HttpStatusCode.OK;
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
【问题讨论】:
-
为什么不能在客户端使用
ReadAsMultipartAsync? -
HttpContentMultipartExtensions 包括 ReadAsMultipartAsync 在 HttpResponseMessage 上不可用。它们仅在 HttpRequestMessage 上可用。
-
这不是真的...那些扩展在
HttpContent上,你应该可以做到response.Content.ReadAsMultipartAsync -
我读到了,但我没有在 MVC 客户端中得到它。 MP 扩展如何与 HttpContent 关联?我在 WebAPI 项目中得到了它们,但在 MVC 中没有。
-
是的,System.Net.Http 就在那里。添加了 Microsoft.AspNet.WebApi.Client nuget 包,现在有多种形式的扩展。
标签: c# asp.net asp.net-web-api httpclient multipartform-data