借助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);
然后它说:
无法对
HttpResponse
消息无效
我正在使用以下方法:
GetJsonAsync() // For HttpGet
SendJsonAsync() // For HttpPost And Put
DeleteAsync() // For HttpDelete
如何在此处验证状态码?
答案 0 :(得分:5)
问题是您正在使用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
答案 1 :(得分:2)
尝试一下:
var response = await Http.SendJsonAsync <HttpResponseMessage>(HttpMethod.Post, "api/Sample/Add", obj);