Web API POST MultipartFormDataContent:响应可以返回多部分内容吗?

时间:2014-01-16 21:44:36

标签: c# asp.net asp.net-web-api httpclient multipartform-data

我正在尝试将一个或多个文件(.doc)发送到ASP.NET Web API 2服务并返回修改后的版本(.docx)。我能够发送文件并获得响应,但我在请求中的HTTPContent服务中使用的HttpContentMultipartExtensions在客户端中无法用于响应。这是开箱即用的可以接线的东西,还是滥用多部分?

有两个应用程序:MVC客户端和Web API服务:

Controller for Client(从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);
        }
    }
}

1 个答案:

答案 0 :(得分:5)

多部分扩展程序是System.Net.Http.Formatting dll的一部分。确保您的客户端安装了nuget包Microsoft.AspNet.WebApi.Client