I am trying to create an application using Blazor and .NET Core 3 with EF Core 3. I have setup a database model and an API for users (/api/users) and browsing to this in chrome returns all of the entities in the database. My GetJson method in the Razor file returns null however.
Here is my Razor code file:
@page "/"
@using LogicX.Shared
@inject HttpClient Http
<h1>Users</h1>
@functions{
User[] _users;
protected override async Task OnInitAsync()
{
var users = await Http.GetJsonAsync<User[]>("/api/users");
_users = users;
}
}
@foreach (var usr in _users)
{
<td>@usr.Username</td>
}
The GetJsonAsync method seems to return null, in spite of records being in the database and in spite of the fact i am able to view the entities in Json format by browsing to /api/users. Is my implementation of this correct and does anyone know how to potentially fix this issue?
Edit: Server Side Code:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class UsersController : Controller
{
private readonly LogicXDbContext _context;
public UsersController(LogicXDbContext context)
{
_context = context;
}
// GET: api/Users
[HttpGet]
public async Task<ActionResult<IEnumerable<User>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<ActionResult<User>> GetUser(int id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
return user;
}
// PUT: api/Users/5
[HttpPut("{id}")]
public async Task<IActionResult> PutUser(int id, User user)
{
if (id != user.Id)
{
return BadRequest();
}
_context.Entry(user).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Users
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return CreatedAtAction("GetUser", new { id = user.Id }, user);
}
// DELETE: api/Users/5
[HttpDelete("{id}")]
public async Task<ActionResult<User>> DeleteUser(int id)
{
var user = await _context.Users.FindAsync(id);
if (user == null)
{
return NotFound();
}
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return user;
}
private bool UserExists(int id)
{
return _context.Users.Any(e => e.Id == id);
}
}
}
Having a forward slash in front of the url is bugged right now, so no requests will go through.
Use api/Users/GetUsers
in your client instead.
Set the Return type on the API to Task<ActionResult<List<User>>>
and change the receiving type to List<User>
instead of User[]
.
Doing this will ensure that the sending and receiving types don't mismatch.
I had the same issue. Make sure that the class you're trying to send is a property with getters and setters:
public string Name { get; set; }