-1

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

        }

    }
0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

So the solution is to send an instance of a class, right? I'm stranger to this because I came from a Javascript/Node js background that is really different from OOP/this.
To me it is the most understandable approach. You have a set of xxxxResult classes where you return whatever you need to the client side. This approach could be easily expanded to return some status code, error message and on the client side scripting you can handle the output easily
2

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
           

        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.