【发布时间】:2015-02-18 04:05:57
【问题描述】:
我有这个 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":" 在 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, IEnumerable1 格式化程序,IFormatterLogger formatterLogger,CancellationToken cancelToken)\r\n 在 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage 请求,类型类型,IEnumerable`1 格式化程序,IFormatterLogger formatterLogger,CancellationToken cancelToken)" }
在询问之前我进行了很多搜索,但找不到任何解决方案。感谢您的帮助。
编辑:
注意:如果我删除“facility”参数,并让该方法仅用于上传文件,则效果很好,但我想将 JSON 和文件一起发布。
【问题讨论】:
-
您好,请问您有解决这个问题的办法吗?我也有同样的问题。
-
@uikrosoft,不要在 api 函数中设置参数(参数)(使其不带参数)。并从帖子正文中获取该函数内的参数值。这对我有用。
-
这里有一个完整的教程:asp.net/web-api/overview/advanced/…
标签: c# asp.net .net asp.net-mvc asp.net-web-api