c# - Web API POST MultipartFormDataContent : Can response return multipartform content?

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

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

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

客户端 Controller (从 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 服务的 Controller :

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);
        }
    }
}

最佳答案

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

关于c# - Web API POST MultipartFormDataContent : Can response return multipartform content?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21173536/

相关文章:

REST API 和 HTTP 状态代码

c# - 在 C# 中,如何按尾数对 double 列表进行排序?

c# - WebView Source - 自动认证

javascript - Jquery Ajax 调用返回 403 状态

css - 如何在所有控件之上显示更新进度控件

html - 如何设置圆形图像?

c# - 如何从 IOwinContext 获取 HttpRequestBase

c# - 在不知道用户名的情况下获取用户特定的路径

c# - 通过整数进行分数计数

c# - 如何从 HttpResponseMessage 中读取 cookie?