Get & Post in ASP.NET Blazor
Solution 1
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
Solution 2
Try this:
var response = await Http.SendJsonAsync <HttpResponseMessage>(HttpMethod.Post, "api/Sample/Add", obj);
Tanwer
Updated on June 23, 2022Comments
-
Tanwer almost 2 years
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
MessageI am using below methods:
GetJsonAsync() // For HttpGet SendJsonAsync() // For HttpPost And Put DeleteAsync() // For HttpDelete
How can I verify the status code here ?
-
Maciej Klemarczyk over 3 yearsJust as a remark, the link in the post does not work anymore. The current address is: github.com/dotnet/blazor/blob/0.1.0/src/… Moreover the Blazor has been moved to the ASP.NET Core repo.
-
Nkosi over 3 years@MaciejKlemarczyk thank you for the update. I have used the link you provided to fix the broken the link in the post.