如何在MVC5 Web API中同时接受文件和数据?

XuDong Peng-MSFT 10,181 信誉分 Microsoft 供应商
2024-01-30T07:42:42.1+00:00

我正在向我的 API 端点发送 POST 请求。 有效负载包括一个文件和一些数据,这是代码:

const formData = new FormData();
formData.append("file", file);
formData.append("data", data);

axios.post(url, formData, {
  headers: {
        'Content-Type': 'multipart/form-data'
  }
});

我的问题是我无法使 API 工作。我试过这个:

[HttpPost]
[Route("Import")]
[Authorize]
public async Task<IHttpActionResult> Import(ImportCustomerRequest request)
{
    //...
    return Ok();
}
public class ImportCustomersRequest
{
   public HttpPostedFileBase File { get; set; }
   public string Data { get; set; }
}

当我尝试使用此 API 时,我总是收到错误码:415 Unsupported Media Type 。

{
  "message": "The request entity's media type 'multipart/form-data' is not supported for this resource.",
  "exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'ImportCustomersRequest' from content with media type 'multipart/form-data'.",
  "exceptionType": "System.Net.Http.UnsupportedMediaTypeException",
  "stackTrace": "   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

我能够通过将其添加到 WebApiConfig.cs 来摆脱原始错误,但现在问题是,我的request对象始终为空:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

谁能帮我定义 API 方法来接受文件+一些数据?

Note: 该问题整理于: How to accept file + data in MVC5 Web API?

ASP.NET API
ASP.NET API
ASP.NET: .NET Framework 中一套用于生成 Web 应用程序和 XML Web 服务的技术。API: 支持两个应用程序相互交互的软件中介。
7 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Zhi Lv - MSFT 32,036 信誉分 Microsoft 供应商
    2024-01-30T09:31:28.5566667+00:00

    你好,

    我能够通过将其添加到 WebApiConfig.cs 来消除原始错误:

    这只会使 ASP.NET 将“multipart/form-data”请求路由到您的控制器。 它无法反序列化表单值并将它们绑定到方法的参数。

      您可以通过 HTML 表单直接将文件上传到 API。参考此文档:在 ASP.NET Web API 中发送 HTML 表单数据:文件上传和多部分 MIME   这是代码示例:

    <form name="form1" method="post" enctype="multipart/form-data" action="/api/test">
        <div>
            <label for="Data">Data</label>
            <input name="Data" type="text" />
        </div>
        <div>
            <label for="File"> File</label>
            <input name="File" type="file" />
        </div>
        <div>
            <input type="submit" value="Submit" />
        </div>
    </form>
    
    public class TestController : ApiController
        {
            [HttpPost]
            public async Task<HttpResponseMessage> PostFormData()
            {
                // Check if the request contains multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
    
                string root = HttpContext.Current.Server.MapPath("~/App_Data");
                var provider = new MultipartFormDataStreamProvider(root);
    
                try
                {
                    // Read the form data.
                    await Request.Content.ReadAsMultipartAsync(provider);
    
                    // This illustrates how to get the file names.
                    foreach (MultipartFileData file in provider.FileData)
                    {
                        Trace.WriteLine(file.Headers.ContentDisposition.FileName);//get FileName
                        Trace.WriteLine("Server file path: " + file.LocalFileName);//get File Path
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, "pass upload file successed!");
                }
                catch (System.Exception e)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
                }
            }
        }
    
    

    如果答案是正确的解决方案,请单击“接受答案”并请投赞成票。如果您对此答案有其他疑问,请点击“评论”。
    注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。
    最好的问候

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助