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
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
CodePudding user response:
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.