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

后端 未结 5 1107
旧巷少年郎
旧巷少年郎 2021-02-15 16:53

I have an action on my web project which calls to an API

    [HttpPost]
    public async Task ExpireSurvey(int id)
    {
        var token =         


        
5条回答
  •  情书的邮戳
    2021-02-15 17:06

    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.

提交回复
热议问题