提供的"HttpContent"实例无效.它没有带有'boundary'参数的'multipart'内容类型标头

Ham*_*mid 15 file-upload asp.net-web-api postman

我正在编写一个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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后我邮递员要求上述行动.我将content-type标头设置为multipart/form-data,但在执行操作期间发生错误.这是错误信息正文:

"提供了无效的'HttpContent'实例.它没有带'border'参数的'multipart'内容类型标头.\ r \nParameter name:content"

我去了邮差标题,但我发现请求标题内容类型in设置为application-json.

邮差截图

谁能帮我?

Pop*_*rei 11

你正在寻找json格式的响应标题,这对你没问题.

您真正的问题在于邮递员请求,因此只需从请求标头中删除"Content-Type:multipart/form-data"条目. 将文件作为表单数据上传并发送请求就足够了.

看看手动设置Content-Type时的情况与不设置时的情况: 在此输入图像描述 在此输入图像描述

Postman知道设置内容类型和边界,因为您只设置了内容类型


Ram*_*usa 0

第一:Postman 在处理基于文件的请求时存在错误。

您可以尝试将其添加到WebApiConfig.cs对我有用的内容中:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
Run Code Online (Sandbox Code Playgroud)