在 .NET API 中在一个响应中发送多个变量

Send multiple variables in one response in .NET APIs

如何在作用域变量、瞬态变量和单例变量中只发送一个响应对象? 我需要在一个请求中发送多个变量。

    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {

        [HttpGet]
        [Route("[controller]/getServices")]
        public ActionResult GetServices()
        {
            var variable1 = "Some code"
            var variable2 = "Some code"
            var variable3 = "Some code"

            // I need like return Ok(variable1, variable2, variable3); 
            // not possible obv

            return Ok(variable1); // Ok
            return Ok(variable2); // unreachable code
            return Ok(variable3); // unreachable code

        }

    }

只需像这样定义一个 class 并将其放在一个名为“Results”的文件夹中,您将在其中保存为相同目的而构建的其他 classes。

public class ServiceResult
{
    public string Variable1 {get;set;}
    public int Variable2 {get;set;}
    public DateTime Variable3 {get;set;}
}

现在在你的控制器中创建这个 class 的实例,设置它的属性和 return 它

[HttpGet]
[Route("[controller]/getServices")]
public ActionResult GetServices()
{
    ServiceResult result = new ServiceResult 
    { 
        Variable1 = "Some string",
        Variable2 = 42,
        Variable3 = DateTime.Today
    };


    return Ok(result);
}

如果你只在 Ok() 上使用它,那么我建议使用匿名类型。

[ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    {

        [HttpGet]
        [Route("[controller]/getServices")]
        public ActionResult GetServices()
        {
            var variable1 = "Some code"
            var variable2 = "Some code"
            var variable3 = "Some code"

            // I need like return Ok(variable1, variable2, variable3); 
            // not possible obv

            return Ok(new { Variable1 = variable1 , Variable2 = variable2 , Variable3 = variable3}); // Ok
           

        }

    }