sam*_*lah 5 c# asp.net-web-api asp.net-core blazor blazor-server-side
我已经通过添加最新的包引用来安装该包。来自https://www.nuget.org/packages/Microsoft.AspNetCore.Blazor.HttpClient/
但我仍然无法找到所需的功能,如..Client.GetJsonAsync
如果我遗漏了什么,你能帮我吗? 谢谢。
我在这里尝试但不能。
public async Task<User> GetUser(string Id)
{
HttpClient client = new HttpClient();
var user = await client.GetJsonAsync($"{BaseUrl}Get-User/{Id}");
return JsonConvert.DeserializeObject<User>(user);
}
Run Code Online (Sandbox Code Playgroud)
1.添加nuget包System.Net.Http.Json
2.使用System.Net.Http.Json添加此命名空间
对我来说没有任何作用,也没有人明确指出这一点。
这些扩展方法存在于System.Net.Http.Json
命名空间中。要使用这些方法,您需要首先添加此包System.Net.Http.Json。然后在using中添加这个System.Net.Http.Json
命名空间。只有这样,json 扩展方法才会与 HttpClient 对象一起出现。
小智 5
1. 在 blazor 服务器应用程序中,当前 HttpClient 类不包含“GetJsonAsync”、“PostJsonAsync”和“PutJsonAsyc”方法。
2.你可以创建一个自定义的HttpClient类来添加这些缺失的方法来处理json数据
public CustomHttpClient : HttpClient
{
public async Task<T> GetJsonAsync<T>(string requestUri)
{
HttpClient httpClient = new HttpClient();
var httpContent = await httpClient.GetAsync(requestUri);
string jsonContent = httpContent.Content.ReadAsStringAsync().Result;
T obj = JsonConvert.DeserializeObject<T>(jsonContent);
httpContent.Dispose();
httpClient.Dispose();
return obj;
}
public async Task<HttpResponseMessage> PostJsonAsync<T>(string requestUri, T content)
{
HttpClient httpClient = new HttpClient();
string myContent = JsonConvert.SerializeObject(content);
StringContent stringContent = new StringContent(myContent, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(requestUri, stringContent);
httpClient.Dispose();
return response;
}
public async Task<HttpResponseMessage> PutJsonAsync<T>(string requestUri, T content)
{
HttpClient httpClient = new HttpClient();
string myContent = JsonConvert.SerializeObject(content);
StringContent stringContent = new StringContent(myContent, Encoding.UTF8, "application/json");
var response = await httpClient.PutAsync(requestUri, stringContent);
httpClient.Dispose();
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
3.现在调用您的剃刀页面:
@inject CustomHttpClient Http
@code{
protected override async Task OnInitializedAsync() {
await Http.GetJsonAsync < Emp[] > ("Your Url");
}
public class Emp
{
public int? ID { get; set; }
public string EmpName { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
方法签名如下:
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri);
Run Code Online (Sandbox Code Playgroud)
因此它是一个通用方法,您必须在调用中包含类型参数。
在你的情况下,这应该看起来像这样:
HttpClient client = new HttpClient();
var user = await client.GetJsonAsync<User>($"{BaseUrl}Get-User/{Id}");
Run Code Online (Sandbox Code Playgroud)
这将已经反序列化对该User
类型的 JSON 响应。
请注意,您需要使用命名Microsoft.AspNetCore.Components
空间才能显示此扩展方法。
归档时间: |
|
查看次数: |
6863 次 |
最近记录: |