0
I am developing an application that consumes data from an API and shows to users, but I am facing an exception:
NullReferenceException: Object reference not set to an instance of an object.
How do I fix it?
Model class:
using System;
using Newtonsoft.Json;
namespace InfoCovid.Models
{
public class Rootobject
{
[JsonProperty("data")]
public Datum[] Data { get; set; }
}
public class Country
{
[JsonProperty("data")]
public Datum Datum { get; set; }
}
public class Datum
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("cases")]
public int Cases { get; set; }
[JsonProperty("confirmed")]
public int Confirmed { get; set; }
[JsonProperty("deaths")]
public int Deaths { get; set; }
[JsonProperty("recovered")]
public int Recovered { get; set; }
[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; set; }
}
}
Class PageModel
(the one who requests the API):
public Datum[] Data { get; private set; }
public IMemoryCache MemoryCache { get; private set; }
public async Task OnGetAsync()
{
try
{
string key_data = "data_key";
if (!MemoryCache.TryGetValue<Datum[]>(key_data, out Datum[] values))
{
var create = RestService
.For<IGetRootobject>
("https://covid19-brazil-api.now.sh/api/report/v1/countries");
var result = await create.GetAsync();
Data = result.Data;
MemoryCache.Set(key_data, Data, System.TimeSpan.FromMinutes(30));
}
else
{
Data = values;
}
}
catch (Exception e)
{
_logger.LogInformation("Erro na requisição http: " + e.Message);
}
}
Page Razor:
@page
@model CitiesModel
@{
ViewData["Title"] = "InfoCovid";
}
<h3>Países</h3>
<div class="card-group">
@foreach (var item in Model.Data)
{
<div class="col-xxl-3 col-lg-3">
<div class="card mb-4" style="background-color: #2E3140;">
<div class="card-body">
<div class="d-flex justify-content-between">
<div class="mr-3">
<div class="text-white">@item.Country</div>
<div class="text-lg text-white font-bold">@item.Deaths</div>
</div>
</div>
</div>
<div class="card-footer d-flex justify-content-between">
<a class="small text-white stretched-link" href="#">View Report</a>
</div>
</div>
</div>
}
</div>
Where are you sending the model to View??? debugged your code? The model is irrelevant to the question... Show your controller or Behind page code
– Leandro Angelo
Learn
IGetRootobject
– Leandro Angelo
I was able to solve the problem. The error was in the model class. I was using property that differed from the return of the api.
– Eduardo Nogueira
I edit the post showing the solution?
– Eduardo Nogueira
you post the answer, but if it’s what I’m imagining it’s a "silly" mistake right?
– Leandro Angelo