【问题标题】:Error while creating new User (Blazor, REST Api)创建新用户时出错(Blazor、REST Api)
【发布时间】:2021-08-07 03:39:56
【问题描述】:

我正在尝试在 .Net 5 中创建新用户。 我做错了什么?

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 在 Swagger 中运行良好,但由于这是我第一次在 Blazor 中工作,因此我正在关注本教程:https://www.pragimtech.com/blog/blazor/create-database-operation-blazor/ 但他使用的是旧版本,所以我不知道这是否是问题所在。 非常感谢任何帮助!

【问题讨论】:

  • 尝试在您的界面和实现中从 Task&lt;IEnumerable&lt;User&gt;&gt; CreateUser(User newUser); 更改为 Task&lt;User&gt; CreateUser(User newUser);
  • 我做了,仍然得到同样的错误

标签: .net http blazor


【解决方案1】:

您正在呼叫PostAsJsonAsync,其签名如下:

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

注意返回值是Task&lt;HttpResponseMessage&gt;。您正在尝试将其分配给 Task&lt;IEnumerable&lt;User&gt;&gt;,因此出现错误。

HttpResponseMessage 包含状态信息和数据。如果返回的数据是 Json 形式的用户对象,您可能可以这样做:

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

【讨论】:

    猜你喜欢
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2018-12-11
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多