0
votes

I'm trying to create new User in .Net 5. What am I doing wrong?

enter image description here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using UserManagment.Models;


namespace UserManagment.Web.Services
{
public class UserService : IUserService
{
    private readonly HttpClient httpClient;

    public UserService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public async Task<IEnumerable<User>> GetUsers()
    {
        return await httpClient.GetFromJsonAsync<User[]>("api/users/");
    }

    public async Task<IEnumerable<User>> CreateUser(User newUser)
    {
        return await httpClient.PostAsJsonAsync<User>("api/users/", newUser);
    }
}

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UserManagment.Models;

namespace UserManagment.Web.Services
{
public interface IUserService
{
    Task<IEnumerable<User>> GetUsers();
    Task<IEnumerable<User>> CreateUser(User newUser);
}
}

POST is working fine in Swagger, but since it's my first time working in Blazor, I'm following this tutorial: https://www.pragimtech.com/blog/blazor/create-database-operation-blazor/ but he is working in older version, so I don't know if that's the problem. Any help much appreciated!

1
Try change from Task<IEnumerable<User>> CreateUser(User newUser); to just Task<User> CreateUser(User newUser); on your interface and in your implementation - Gilvan JĂșnior
i did, still get the same error - aurora

1 Answers

0
votes

You are calling PostAsJsonAsync which has the following signature:

public static Task<HttpResponseMessage> PostAsJsonAsync<T>(
    this HttpClient client,
    string requestUri,
    T value
)

Note the return value is a Task<HttpResponseMessage>. You are trying to assign this to a Task<IEnumerable<User>>, hence the error.

A HttpResponseMessage contains status info and data. If the data returned is a user object as Json, you may be able to something like:

public async Task<User> CreateUser(User newUser)
{
 var response = await this.HttpClient.PostAsJsonAsync<User>("api/users/", newUser);
 return await response.Content.ReadFromJsonAsync<User>();
}