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 can I return API Messages in ASP.NET MVC?

I have some message in the API response. I want to return the message to user. I cannot find how can I do it.

Sample Controller

[HttpGet]
public async Task<IActionResult> ListCountries()
{
    List<Country> countries = new List<Country>();
    var response = await _client.GetAsync("countries/getall");

    if (response.IsSuccessStatusCode)
    {
        string apiResponse = await response.Content.ReadAsStringAsync();
        var JsonData = JsonConvert.DeserializeObject<JsonCountryData>(apiResponse);
        countries = JsonData.Data;
    }
    return View(countries);
}

Country Model

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

namespace EVisaProject.Models
{
    public class CountryModel
    {
        public int Id { get; set; }
        public string CountryName { get; set; }
    }

    public class JsonCountryData
    {
        public List<CountryModel> Data { get; set; }
    }
}

API

enter image description here

>Solution :

Because you’re not de-serializing the property. Look at the object you’re de-serializing the JSON data into:

public class JsonCountryData
{
    public List<CountryModel> Data { get; set; }
}

Notice that it contains a property called Data. Which is why you can access the Data property. You can’t access the Success or Message properties because you haven’t added them to the model, so they don’t exist.

In order to use them, add them to the model so they exist:

public class JsonCountryData
{
    public List<CountryModel> Data { get; set; }
    public bool Success { get; set; }
    public string Message { get; set; }
}

Once they exist, you’ll be able to use them:

var JsonData = JsonConvert.DeserializeObject<JsonCountryData>(apiResponse);
// after here you can access the "Success" and "Message" properties on the "JsonData" object

There’s nothing special about the "message" property in the JSON response. You would access it exactly the same way that you already access the "data" property.

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