Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send multiple variables in one response in .NET APIs

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

        }

    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading