DEV Community

Egor Pavlikhin
Egor Pavlikhin

Posted on

Map JSON object to Controller Action with multiple parameters

Last week I was surprised to find out that .Net Core still doesn't support something that every JavaScript/TypeScript framework does: mapping JSON object to multiple action parameters just isn't supported. You are supposed to define a Model class, add it as a single parameter and mark it with [FromBody].

{ "a": "a", "b": "b" }

This just didn't sit right with me. Why declare a whole new class for every single Action with just a few parameters. What do I need to do to have a controller method as simple as this?

[HttpPost]
public async Task SometMethod(string a, string b) 
{
  return Ok();
}

I couldn't find an answer, so I wrote my own package to do that.
You can download it here or view source here.

It's very simple, and quite slow for now (as it re-parses the whole request for every parameter), but does the job for simple cases.

Usage

Given JSON

{ "a": "a", "b": { "c": "value" } }

Step 1.
Add attribute JsonParameters to your action

[HttpPost("two")]
[JsonParameters]
public async Task<IActionResult> TwoParameters(string a, dynamic b)
{
    Console.WriteLine(b.c);
    return Ok();
}

Step 2.
Enhoy simplified workflow.

Thanks

Thanks to tchivs for providing code to map to dynamic types

Top comments (0)