获取和发布ASP.NET Blazor

Tan*_*wer 3 c# asp.net-core-webapi blazor asp.net-core-2.1 blazor-server-side

借助互联网上的一些示例,我可以开发ASP.NET Core Hosted 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();
}
Run Code Online (Sandbox Code Playgroud)

在下面的行中:

await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);     
Run Code Online (Sandbox Code Playgroud)

如何查看此HTTP呼叫的状态代码?

如果API调用中出现任何问题而不是我想显示消息.

但当我这样做时:

 HttpResponseMessage resp = await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);
Run Code Online (Sandbox Code Playgroud)

然后它说:

无法将HttpResponse消息转换为消息

我使用以下方法:

GetJsonAsync() // For HttpGet
SendJsonAsync() // For HttpPost And Put
DeleteAsync() // For HttpDelete  
Run Code Online (Sandbox Code Playgroud)

如何在此验证状态代码?

Nko*_*osi 6

问题是你正在使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

普通的HttpClientAPI仍然存在,可以像在那些扩展方法中一样使用.

这些扩展方法只是包装默认HttpClient调用.

如果您希望能够访问响应状态,则需要编写自己的包装器来公开所需的功能,或者只使用默认的API