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

How to return int,string and json of data in ASP.NET Core Web API

I want to return a number, a string, and a json from the data in output of an ASP.NET Core Web API.

I have this class:

public class Customer
{
    public int id { get; set; }
    public string name { get; set; }

    public Customer(int _id, string _name)
    {
        id = _id;
        name = _name;
    }
}

And my API method is:

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

[Microsoft.AspNetCore.Mvc.HttpGet("myAPI")]
public IActionResult myAPI()
{
    List<Customer> listName = new List<Customer>();
    listName.Add(new Customer(1, "name1"));
    listName.Add(new Customer(2, "name2"));
    listName.Add(new Customer(3, "name3"));

    int codeResult = 222;
    string message = "mymessage";

    return //how to return codeResult,message, Json(listName)
}

I expect the output to be as below

{
    codeResult: 222,
    message: "mymessage",
    data: [
             { "id": 1, "name": "name1" }...
    ]
}

>Solution :

try this:

    [Microsoft.AspNetCore.Mvc.HttpGet("myAPI")]
    public IActionResult myAPI()
    {
        List<Customer> listName = new List<Customer>();
        listName.Add(new Customer(1, "name1"));
        listName.Add(new Customer(2, "name2"));
        listName.Add(new Customer(3, "name3"));

        int codeResult = 222;
        string message = "mymessage";
        return Ok(new { codeResult = codeResult, message = message, data = listName});
    }

This is the result:

enter image description here

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