1

GetFromJsonAsync当我们使用命名的 HttpClients 时,我们没有可用的方法有什么原因吗?当我切换到命名 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);
        }

谢谢法赫德穆拉吉

4

2 回答 2

3

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

using System.Net.Http.Json;

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

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

于 2020-07-02T10:55:21.183 回答
1

添加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);
}
于 2020-07-02T13:01:39.057 回答