How to use [FromBody] and [FromForm] on the same url?

Viewed 2166

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;
    }
}
1 Answers

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.

Related