3

I have WEbAPI2 back end.

I try to send form data from postman

enter image description here

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

enter image description here

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

Sukhomlin Eugene
  • 183
  • 4
  • 19
  • Seems that you're doing POST to incorrect action method URL. Check your `$.ajax` or `$http` request, perhaps you just need a GET method or you need to set `Content-Type: application/json` header for AJAX request. – Tetsuya Yamamoto Jul 13 '17 at 06:41
  • I don't do AJAX request, I do request from app@TetsuyaYamamoto – Sukhomlin Eugene Jul 13 '17 at 06:46
  • Have you using `HttpPostedFileBase` placeholder for Web API controllers instead of MVC controllers? You need to use `HttpContext.Current.Request.Files` for Web API, or place this in WebApiConfig.cs: `config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));`. – Tetsuya Yamamoto Jul 13 '17 at 06:51

2 Answers2

6

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

garethb
  • 3,951
  • 6
  • 32
  • 52
1

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

Postman Snap

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
Ajay
  • 643
  • 2
  • 10
  • 27