简体   繁体   English

将表单数据和文件发布到ASP.NET Web API

[英]Posting form-data AND a file to ASP.NET Web API

I have this ASP.NET Web API method, and I want to post an object and in the same time, a file! 我有这个ASP.NET Web API方法,我想发布一个对象,同时,一个文件!

    public async Task<IHttpActionResult> Post(Facility facility)
    {
        if (!ModelState.IsValid)
            return BadRequest();

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

            // 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);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            // Logic
            // Login

        return Ok(facilityManager.Insert(facility));
    }

And I want to call it, so I send this http request with fiddler: 我想打电话给它,所以我用fiddler发送这个http请求:

Header: 标题:

Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Host: localhost:44301
Content-Length: 3279

Body: 身体:

---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="credits.txt"
Content-Type: text/plain

<@INCLUDE *C:\Program Files (x86)\Fiddler2\credits.txt*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="facility"
Content-Type: application/json
{
    "FacilityTypeId":"1"
}
---------------------------acebdf13572468--

I get an 415 error code with response text: 我收到带有响应文本的415错误代码:

{"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 'Facility' 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.Net.Http.HttpContentExtensions.ReadAsAsync(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)"} {“message”:“此资源不支持请求实体的媒体类型'multipart / form-data'。”,“exceptionMessage”:“没有MediaTypeFormatter可用于从具有媒体类型的内容中读取”Facility“类型的对象'multipart / form-data'。“,”exceptionType“:”System.Net.Http.UnsupportedMediaTypeException“,”stackTrace“:”at System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)\\ r \\ n在System.Web.Http 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable 1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)\\ r \\ n .ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)“}

I searched a lot before asking but couldn't find any solution. 在询问之前我搜索了很多,但找不到任何解决方案。 Thnaks for helping. 向你求助。

EDIT: 编辑:

A note: If I remove the "facility" parameter, and let the method only for uploading the file, it works perfect, but I want to post JSON and a file together. 注意:如果我删除“facility”参数,并让该方法仅用于上传文件,它的工作完美,但我想将JSON和文件一起发布。

"mulitpart/form-data" so we register the UploadMultipartMediaTypeFormatter “mulitpart / form-data”所以我们注册了UploadMultipartMediaTypeFormatter

public class UploadMultipartMediaTypeFormatter : MediaTypeFormatter
{
    UploadMultipartMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
    }
}

* register in global.asax or (see sandbox code) *在global.asax中注册或(参见沙盒代码)

config.Formatters.Add(new UploadMultipartMediaTypeFormatter());

The WebApi will now call MediaTypeFormatter.ReadFromStreamAsync and we can call the HttpContent.ReadAsMultipartAsync extension from there. WebApi现在将调用MediaTypeFormatter.ReadFromStreamAsync,我们可以从那里调用HttpContent.ReadAsMultipartAsync扩展。

I had the same problem. 我有同样的问题。 Solved by MultipartDataMediaFormatter for ASP.NET WebApi. 由ASP.NET WebApi的MultipartDataMediaFormatter解决。 How to use: 如何使用:

  1. Find and install from Nuget packages MultipartDataMediaFormatter . 从Nuget包中找到并安装MultipartDataMediaFormatter
  2. Add current formatter to WebApi formatters collection: 将当前格式化程序添加到WebApi格式化程序集合:

    • if WebApi hosted on IIS (on Application Start). 如果WebApi托管在IIS上(在Application Start上)。 :
      • GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
    • if WebApi is self-hosted: 如果WebApi是自托管的:

      • new HttpSelfHostConfiguration(<url>).Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());

After that you can post objec with file together in one model. 之后,您可以在一个模型中将objec与文件一起发布。

Note : In Nuget packages version 1.1.0 is not the last. 注意 :在Nuget包中,版本1.1.0不是最后一个。 They are not updated yet. 它们尚未更新。 Maybe possible to install latest version manually. 也许可以手动安装最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据发布到asp.net Web API - Posting data to asp.net Web API 如何发送 multipart/form-data 到 ASP.NET Core Web API? - How to send multipart/form-data to ASP.NET Core Web API? 如何将多部分表单数据列表发布到ASP.NET Web API操作 - how to post list of multipart form-data to asp.net web api action 如何从上传到 api asp.net 的 multipart/form-data 音频文件中检索元数据 - how to retrieve meta data from a multipart/form-data Audio file upload to api asp.net 将文件从 ASP.NET MVC 4.6 应用程序发布到 ASP.NET Core Web API - Posting a file from ASP.NET MVC 4.6 application to ASP.NET Core Web API 如何将请求从Asp.net MVC发送到multipart / form-data类型的外部api - how to send request from Asp.net MVC to external api in multipart/form-data type 如何在 Asp Net Core Web Api 中发布多部分表单数据的对象列表 - How to post list of objects multipart form-data in Asp Net Core Web Api 从 ASP.NET Core HttpContext.Request 的 multipart/form-data 内容读取 excel 文件? - Reading excel file from ASP.NET Core HttpContext.Request of multipart/form-data content? ASP.NET 将 multipart/form-data 发送到 Power Automate - ASP.NET send multipart/form-data to Power Automate ASP .NET 核心 - 将上传的文件作为多部分/表单数据发送到 API 端点 - ASP .NET Core - Send uploaded file as multipart/form-data to API endpoint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM