Tanwer
Tanwer

Reputation: 1583

Get & Post in ASP.NET Blazor

With the help of a few samples available on the internet, I am able to develop a ASP.NET Core Hosted Blazor Application.

But While Calling an api as follow

 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();
}

In the line below:

await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);     

How can I check status code of this HTTP call?

If there occurs any problem in API call than I want to display a message.

But when I do:

 HttpResponseMessage resp = await Http.SendJsonAsync(HttpMethod.Post, "api/Sample/Add", obj);

Then it says:

can not cast void to HttpResponse Message

I am using below methods:

GetJsonAsync() // For HttpGet
SendJsonAsync() // For HttpPost And Put
DeleteAsync() // For HttpDelete  

How can I verify the status code here ?

Upvotes: 4

Views: 20744

Answers (2)

Nkosi
Nkosi

Reputation: 247571

The thing is that you are using blazor's HttpClientJsonExtensions extensions,

Which internally usually calls

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);
    }
}

The GET requests use HttpContext.GetStringAsync internally

public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
    var responseJson = await httpClient.GetStringAsync(requestUri);
    return JsonUtil.Deserialize<T>(responseJson);
}

while the normal HttpClient API still exists and can be used just as in those extension methods.

Those extension methods simply wrap the default HttpClient calls.

If you desire to have access to response status you would need to write your own wrappers that expose the desired functionality or just use the default API

Upvotes: 8

enet
enet

Reputation: 45764

Try this:

 var response = await Http.SendJsonAsync <HttpResponseMessage>(HttpMethod.Post, "api/Sample/Add", obj);

Upvotes: 2

Related Questions