locked
Using urlencoded body in Web API RRS feed

  • Question

  • User-1262787652 posted
    Creating ASP.NET 5 MVC Core API.
    
    Browser passes url-encoded _dokdata array as json content to API controller using POST method. 
    
    Request header:
    
        content-type: application/x-www-form-urlencoded; charset=UTF-8
    
    Request body contains single _dokdata property whose content is name/value object array:
    
        _dokdata: [{"name":"Kuupaev","value":"2021-11-07"},{"name":"Test","value":"abs"}]
    
    It is passed in URL encoded format from external applications which cannot changed:
    
        _dokdata=%5B%7B%22name%22%3A%22Kuupaev%22%2C%22value%22%3A%222021-11-07%22%7D%2C%7B%22name%22%3A%22Test%22%2C%22value%22%3A%22abs%22%7D%2C%7B%22name%22%3A%22Tasudok%
        ...
    
    API controller which uses it is defined as :
    
        [ApiController, Authorize]
        public class DetailApiController : ControllerBase
        {
            [Route("Detail/SaveDocument"), HttpPost]
            public async Task<dynamic> SaveDocument(string _dokdata) {
          ....
    
    Calling controller throws unsupported media type error:
    
        {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13",
          "title":"Unsupported Media Type",
          "status":415,
          "traceId":"00-f88a7bb94f8f344dac5077043fdda061-59aca1a5149fce4f-00"
         }
    
    How to use this content in .NET 5 MVC API ?

    Saturday, May 15, 2021 2:49 PM

All replies

  • User475983607 posted

    The 4XX errors are caused by the client request.  You did not share the client code or the authorization being used.  It is difficult to provide meaningful advice when the code that causes the error is not shared. 

    I did find your Web API is missing the [FromBody] attribute.  Model binding is an openly published standard in .NET 5; https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0.

    [HttpPost]
    [Route("Detail/SaveDocument")]
    public IActionResult SaveDocument([FromForm]string _dokdata)
    {
        return Ok(new { dokdata  = _dokdata });
    }

    Saturday, May 15, 2021 5:21 PM