【问题标题】:@inject HttpClient httpClient vs builder.Services.AddHttpClient in Blazor@inject HttpClient httpClient 与 Blazor 中的 builder.Services.AddHttpClient
【发布时间】:2020-10-22 22:47:38
【问题描述】:

当我们使用命名的 HttpClients 时,我们没有可用的 GetFromJsonAsync 方法有什么原因吗?当我切换到命名 HttpClients 时,我必须安装 NewtonSoftJson 来反序列化响应。

注入 Razor 组件

@inject HttpClient httpClient

@code{

    public async Task GetProfileAsync()
    {
        User user = await httpClient.GetFromJsonAsync<User>("user/getprofile/10");
    }
}

注入服务/类

        public ProfileViewModel(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task GetProfileAsync()
        {
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, "user/getprofile/10");
            var response = await _httpClient.SendAsync(requestMessage);
            var responseBody = await response.Content.ReadAsStringAsync();            
            User user = JsonConvert.DeserializeObject<User>(responseBody);
        }

谢谢 法赫德·穆拉吉

【问题讨论】:

  • 好的,让我改一下。

标签: c# .net blazor blazor-client-side blazor-webassembly


【解决方案1】:

它们是扩展方法。只需添加

using System.Net.Http.Json;

当您确实需要手动(反)序列化时,首选System.Text.Json。它现在是默认和首选的 API。

NewtonSoft 仍有一些用例,但它们正在迅速消失。

【讨论】:

  • 检查您的 _Imports.razor 文件。
  • 我用 Newtonsoft,S.T.Json 就是不够好。
  • 我自己并没有进行太多比较,但 SysText 应该更快。和未来。但是有一些遗留的 Web API 需要调整。通常关于camelCasing开/关。
【解决方案2】:

添加 using System.Net.Http.Json 以使用扩展方法

命名空间:

using System.Net.Http;
using System.Net.Http.Json;

方法:

public ProfileViewModel(HttpClient httpClient)
{
    _httpClient = httpClient;
}

public async Task GetProfileAsync()
{
    User user = await _httpClient.GetFromJsonAsync<User>("user/getprofile/10");    
}

public async Task UpdateProfile()
{        
    await _httpClient.PutAsJsonAsync("user/updateprofile/10", user);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2021-04-21
    相关资源
    最近更新 更多