我有这个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));
}
,我想打电话给它,所以我送与小提琴手这个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)“}
我询问了很多,但没有找到任何解决方案。 Thnaks帮助。
编辑:
的说明:如果我只上载的文件中删除“设施”参数,让方法,它的作品完美,但我想张贴JSON和文件一起。
你好,你有解决这个问题的办法吗?我有同样的问题。 – uikrosoft 2015-03-13 09:18:26
@uikrosoft,不要在api函数中设置参数(参数)(不带参数)。并从帖子主体获取你的参数值。这对我有效。 – Hashem 2015-03-16 08:05:27
这里是一个完整的教程:http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2 – 2015-06-17 08:09:54