3

Client can send me data in JSON or application/x-www-form-urlencoded format. How can i process this requests without separation to diffrent urls? I tried two cases. It don't work; Case 1:

[Route ( "api/[controller]" )]
[ApiController]
public class FirstController : ControllerBase
{
    [HttpPost]
    public string SomePostFromBody ( [FromBody] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }

    [HttpPost]
    public string SomePostFromForm ( [FromForm] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }
}

Case 2:

[Route ( "api/[controller]" )]
[ApiController]
public class FirstController : ControllerBase
{
    [HttpPost]
    public string SomePost( [FromBody][FromForm] TestClass obj )
    {
        return obj.Prop1 + obj.Prop2;
    }
}
Igor
  • 60,821
  • 10
  • 100
  • 175
Nodon
  • 967
  • 11
  • 24
  • See also https://stackoverflow.com/questions/50453578/asp-net-core-fromform-and-frombody-same-action – Igor Aug 28 '18 at 10:49
  • 2
    But there's an answer here that contradicts that, using Consumes: https://stackoverflow.com/a/51735331/243245 – Rup Aug 28 '18 at 10:51
  • Maybe this can help you: https://massivescale.com/web-api-routing-by-content-type/ – Hans Kilian Aug 28 '18 at 10:51
  • @Igor i saw it. I don't need to use only one action. I can make another method or contoller – Nodon Aug 28 '18 at 10:55

1 Answers1

1

Why don't you just manually read out the values?

e.g.

[HttpPost]
public string SomePost()
{
    // Check if it's a Form value
    if(Request.Form != null) { // do something }
    else if(Request.Body != null) { // do something }
}

Note: the code above might not compile, I just quickly wrote it in here.

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83