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

心已入冬 提交于 2019-12-05 11:15:26

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

you can do it with a dictionary

Dictionary<string, object> dict = new Dictionary<string, object>();
dict["id"] = 1
dict["date"] = DateTime.Now;

JsonConvert.SerializeObject(dict);

Based on the answers above, I got the following code working. Hope this helps someone! (thanks to others of course for getting me on the right track)

/// <summary>
/// Post api/dostuff/{id}
[HttpPost]
[Route("dostuff/{id}")]
public async Task<IActionResult> DoStuff([FromBody]Model model, int id)
{
    // Both model and id are available for use!
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!