我正在编写一个 web api,它有一个 post 方法接受从 UI 上传的文件。
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent("form-data"))
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
var streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
return streamProvider.FileData
.Select(file => new FileInfo(file.LocalFileName))
.Select(fi => "File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)")
.ToList();
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
然后我通过 postman 向上述行动发出请求。
我将内容类型 header 设置为 multipart/form-data
但在执行 Action 时发生错误。
这是错误消息正文:
"提供的 'HttpContent' 实例无效。它没有带有 '边界' 参数的 'multipart' 内容类型 header 。\r\n参数名称:内容"
我去了 postman header ,但我发现请求 header 内容类型设置为 application-json。
谁能帮我?
最佳答案
您正在查看 json 格式的响应 header ,这对您来说没问题。
您真正的问题在于 postman 请求,因此只需从请求 header 中删除“Content-Type: multipart/form-data”条目。
上传一个文件作为表单数据并发送请求就足够了 .
看看当您手动设置 Content-Type 与不设置时会发生什么:
Postman 知道要同时设置内容类型和边界,因为您只设置了内容类型
关于file-upload - 提供的 'HttpContent' 实例无效。它没有带有 'multipart' 参数的 'boundary' 内容类型 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24503961/