Pass multiple parameters in a POST API without using a DTO class in .Net Core MVC

You can use anonymous types like this

var x = new { id = 2, date = DateTime.Now };
var data = JsonConvert.SerializeObject(x);

When receiving the data, you can only have one [FromBody] parameter. So that doesn't work for receiving multiple parameters (unless you can put all but one into the URL). If you don't want to declare a DTO, you can use a dynamic object like this:

[HttpPost]
public void Post([FromBody] dynamic data)
{
    Console.WriteLine(data.id);
    Console.WriteLine(data.date);
}

Don't overdo using anonymous types and dynamic variables though. They're very convenient for working with JSON, but you lose all type checking which is one of the things that makes C# really nice to work with.


I think it would be helpful to recognize that ASP.NET Core is REST-based and REST fundamentally deals with the concept of resources. While not an unbreakable rule, the general idea is that you should have what you're calling DTOs here. In other words, you're not posting distinct and unrelated bits of data, but an object that represents something.

This becomes increasingly important if you start mixing in things like Swagger to generate documentation for your API. The objects you create become part of that documentation, giving consumers of your API a template for follow in the development of their apps.

Long and short, I'd say embrace the concept of resources/objects/DTOs/whatever. Model the data your API works with. It will help both you as a developer of the API and any consumers of your API.


You can pass multiple parameters in as URL as below example

Parameter name must be the same (case-insensitive), If names do not match then values of the parameters will not be set.

[HttpPost]
[Route("{surveyId}/{expiryDate}")]
public IActionResult Post(int surveyId, DateTime expiryDate)
{
    return Ok(new { surveyId, expiryDate });
}

Call URL

http://localhost:[port]/api/[controller]/1/3-29-2018