Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labeling values returned from API

Tags:

c#

This method returns a bool and a string -

public (bool active, string name) Report() 
{
}

From my controller, I call it like this -

public IActionResult Credit([FromBody] Data data)
{
    return Ok(Report())
}

The response I get is something like this -

{
    "item1": false,
    "item2": "Your name"
}

How do I get this response instead -

{
    "Active": false,
    "Name": "Your name"
}
like image 202
Aaron Avatar asked Feb 16 '26 03:02

Aaron


1 Answers

The quick and easy way would be to return an anonymous type, taking the values from the returned tuple

public IActionResult Credit([FromBody] Data data) 
{
    //...
    var report = Report();
    return Ok(new 
    {
        Active = report.active,
        Name = report.name
    })
}

Ideally you should return a strongly typed model that can be returned from the API

public class ReportModel 
{
    public string Name { get;set; }
    public bool Active { get;set; }
}

and update accordingly

public ReportModel Report()  
{
    //...
}

public IActionResult Credit([FromBody] Data data) 
{
    //...
    var report = Report();
    return Ok(report);
}
like image 182
Nkosi Avatar answered Feb 17 '26 15:02

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!