Accept x-www-form-urlencoded in Web API .Net Core

后端 未结 4 815
生来不讨喜
生来不讨喜 2020-12-31 02:19

I have a .Net Core Web API that is returning a 415 Unsupported Media Error when I try to post some data to it that includes some json. Here\'s part of what is returned in t

相关标签:
4条回答
  • 2020-12-31 02:28

    I had the same problem. FormDataCollection has no default constructors which is required by Formatters. Use IFormCollection instead

    0 讨论(0)
  • 2020-12-31 02:32

    Try using [FromForm] instead of [FromBody]

    public IActionResult Post([FromForm] PlayerPackage playerPackage)
    

    FromBody -> If you binding from JSON

    FromForm -> If you binding from Form parameters

    NOTE 1:

    You can also remove [FromBody] altogether and trial it then. Because you are expecting form-urlencoded should tell it to bind to object.

    0 讨论(0)
  • 2020-12-31 02:50

    For PlayerPackage, the request should send a PlayerPackage Json Object, based on your description, you could not control the request which is posted from other place.

    For the request, its type is application/x-www-form-urlencoded, it will send data with {"status":"incomplete","score":""} in string Format instead of Json object. If you want to accept {"status":"incomplete","score":""}, I suggest you change the method like below, and then conver the string to Object by Newtonsoft.Json

        [HttpPost]
        [Route("~/api/trackAllInOne/set")]
        [Consumes("application/x-www-form-urlencoded")]
        public IActionResult Post([FromForm] string data)
        {
            PlayerPackage playerPackage = JsonConvert.DeserializeObject<PlayerPackage>(data);
            return Json(data);
        }
    
    0 讨论(0)
  • 2020-12-31 02:51

    This did the trick for me:

    [HttpPost]
    [Consumes("application/x-www-form-urlencoded")]
    public IActionResult Post([FromForm]IFormCollection value)
    

    Hope it helps

    0 讨论(0)
提交回复
热议问题