Invalid 'HttpContent' instance provided. I

2019-02-21 12:25发布

I'm writing a web api that have a post method accepting files from uploaded from 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);
        }
    }

then i post a request to above action by postman. I set content-type header to multipart/form-data but an error occures during execution of action. here is error message body :

"Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter.\r\nParameter name: content"

i went to the postman headers but i found that request header content-type in was set to application-json.

Postman screenshot

can anyone help me?

2条回答
Ridiculous、
2楼-- · 2019-02-21 13:21

You are looking on the response header which is json format and this is ok for you.

Your real problem is with the postman request, so just remove the 'Content-Type: multipart/form-data' entry from request header. It's enough to upload a file as form-data and send the request.

Look what happen when you set the Content-Type manually vs. when you not: enter image description here enter image description here

Postman knows to set both the content type and boundary, since you set only the content type

查看更多
The star\"
3楼-- · 2019-02-21 13:21

First: Postman have a bug in handling file-based requests.

You can try adding this to your WebApiConfig.cs it worked for me:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
查看更多
登录 后发表回答