'multipart/form-data' is not supported for

2020-07-27 02:47发布

问题:

I have WEbAPI2 back end.

I try to send form data from postman

But get this error

"No MediaTypeFormatter is available to read an object of type 'StartWorkingDay' from content with media type 'multipart/form-data'.",

Here is code of my controller

// POST: api/StartWorkingDays
[ResponseType(typeof(StartWorkingDay))]
public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.StartWorkingDays.Add(startWorkingDay);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
}

When I send it via raw data, all okay

How I can make it receive multipart/form-data?

回答1:

Taken from MSDN

application/x-www-form-urlencoded

Form data is encoded as name/value pairs, similar to a URI query string. This is the default format for POST.

multipart/form-data

Form data is encoded as a multipart MIME message. Use this format if you are uploading a file to the server.

Use enctype x-www-form-urlencoded, not form-data in postman



回答2:

Select form-data in postman. Add key "startWorkingDay", and deserialize the request parameter in your requisite function. And, you are done.

Code:

    // POST: api/StartWorkingDays
        [System.Web.Http.AcceptVerbs("POST")]
        [System.Web.Http.HttpPost]
        [ResponseType(typeof(StartWorkingDay))]
        public IHttpActionResult PostStartWorkingDay()
        {
            var startWorkingDay = JsonConvert.DeserializeObject<StartWorkingDay>(HttpContext.Current.Request.Form["startWorkingDay"]);
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}

            db.StartWorkingDays.Add(startWorkingDay);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
        }


  [1]: https://i.stack.imgur.com/AF5YH.png