Home > OS >  Send multiple variables in one response in .NET APIs
Send multiple variables in one response in .NET APIs

Time:04-10

How can i send only one response object within scoped, transient and singleton variable? I need like sending multiple variables in only one request.

    [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

        }

    }

CodePudding user response:

Just define a class like this and put it in a folder named "Results" where you will keep other classes built for the same purposes.

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

Now in your controller just create the instance of this class, set its properties and return it

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


    return Ok(result);
}

CodePudding user response:

If you are using this only on Ok() then I would suggest to use Anonymous type.

[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
           

        }

    }

  • Related