借助 Internet 上提供的一些示例,我能够开发 ASP.NET Core 托管的 Blazor 应用程序。
但是在调用 api 时如下所示
private async Task Refresh()
{
li.Clear();
li = await Http.GetJsonAsync<SampleModel[]>("/api/Sample/GetList");
StateHasChanged();
}
private async Task Save()
{
await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);
await Refresh();
}
在下面一行中:
await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);
如何检查此 HTTP 调用的状态代码?
如果 API 调用出现任何问题,我想显示一条消息。
但是当我这样做的时候:
HttpResponseMessage resp = await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);
然后它说:
can not cast void to
HttpResponse
Message
我正在使用以下方法:
GetJsonAsync() // For HttpGet
SendJsonAsync() // For HttpPost And Put
DeleteAsync() // For HttpDelete
如何验证这里的状态码?
最佳答案
问题是您正在使用 blazor 的 HttpClientJsonExtensions
扩展,
内部通常调用
public static Task SendJsonAsync(this HttpClient httpClient, HttpMethod method, string requestUri, object content)
=> httpClient.SendJsonAsync<IgnoreResponse>(method, requestUri, content);
public static async Task<T> SendJsonAsync<T>(this HttpClient httpClient, HttpMethod method, string requestUri, object content)
{
var requestJson = JsonUtil.Serialize(content);
var response = await httpClient.SendAsync(new HttpRequestMessage(method, requestUri)
{
Content = new StringContent(requestJson, Encoding.UTF8, "application/json")
});
if (typeof(T) == typeof(IgnoreResponse))
{
return default;
}
else
{
var responseJson = await response.Content.ReadAsStringAsync();
return JsonUtil.Deserialize<T>(responseJson);
}
}
GET 请求在内部使用 HttpContext.GetStringAsync
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
var responseJson = await httpClient.GetStringAsync(requestUri);
return JsonUtil.Deserialize<T>(responseJson);
}
虽然普通的 HttpClient
API 仍然存在并且可以像在那些扩展方法中一样使用。
这些扩展方法只是包装了默认的 HttpClient
调用。
如果您希望访问响应状态,您需要编写自己的包装器来公开所需的功能,或者只使用默认 API
关于c# - 在 ASP.NET Blazor 中获取和发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53944604/