在POST API中传递多个参数,而无需使用.Net Core MVC中的DTO类 [英] Pass multiple parameters in a POST API without using a DTO class in .Net Core MVC

查看:1215
本文介绍了在POST API中传递多个参数,而无需使用.Net Core MVC中的DTO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对自己的Web项目有一个调用API的操作

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

    [HttpPost]
    public async Task<IActionResult> ExpireSurvey(int id)
    {
        var token = await HttpContext.GetTokenAsync("access_token");

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var path = "/api/forms/ExpireSurvey";
            var url = Domain + path;
            var data = JsonConvert.SerializeObject(id);
            HttpContent httpContent = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PutAsync(url, httpContent);

            return Json(response);
        }
    }

在API项目中,收到的信息如下:

In the API project this is received as follows:

[HttpPut]
    public IActionResult ExpireSurvey([FromBody] int surveyId)
    {
        _repository.ExpireSurvey(surveyId, expiryDate);
        return Ok();
    }

这很好用-但是,说我想传入一个int id和一个DateTime变量,我该如何序列化并将它们都传递给HttpContent?我可以使用DTO对象来完成此操作,但是当只有两个字段时,我不想设置DTO对象.

This works fine - however, say I want to pass in an int id and a DateTime variable, how do I serialise and pass them both into the HttpContent? I can do it with a DTO object, but I don't want to be setting up DTO objects when there is only two fields.

推荐答案

您可以使用像这样的匿名类型

You can use anonymous types like this

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

接收数据时,只能有一个[FromBody]参数.因此,这对于接收多个参数不起作用(除非您可以将除一个以外的所有参数都放入URL中).如果您不想声明DTO,则可以使用这样的动态对象:

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);
}

不过不要过度使用匿名类型和动态变量.它们对于使用JSON非常方便,但是您丢失了所有类型检查,这是使C#真正易于使用的原因之一.

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.

这篇关于在POST API中传递多个参数,而无需使用.Net Core MVC中的DTO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆