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

时间:2014-12-19 08:41:16

标签: c# asp.net .net asp.net-mvc asp.net-web-api

我有这个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));
    }

我想打电话给它,所以我用fiddler发送这个http请求:

标题:

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

体:

---------------------------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--

我收到带有响应文本的415错误代码:

  

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

我在询问之前搜索了很多,但找不到任何解决方案。向你求助。

修改

注意:如果我删除“facility”参数,并让该方法仅用于上传文件,它的工作原理很完美,但我想将JSON和文件一起发布。

1 个答案:

答案 0 :(得分:3)

&#34; mulitpart /格式数据&#34;所以我们注册了UploadMultipartMediaTypeFormatter

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

*在global.asax中注册或(参见沙箱代码)

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

WebApi现在将调用MediaTypeFormatter.ReadFromStreamAsync,我们可以从那里调用HttpContent.ReadAsMultipartAsync扩展。