How to do synchronous calling of HttpClient in Blazor

Posted 3 years ago by manikanta
Edited 3 years ago
0

I want to call an API synchronously in Blazor, But it is not working. Is there a way call API synchronously. Please find the below code.

currently using asynchronous call as mentioned below:  

if(HttpClient == null)

{

HttpClient = new HttpClient();

HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userContext.Token);

}

var json = JsonConvert.SerializeObject(request);

HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");

 

var httpResponse = await HttpClient.PostAsync(api, content);

 

httpResponse.EnsureSuccessStatusCode();

 

var response = await httpResponse.Content.ReadAsStringAsync();

var parsedResult = JObject.Parse(response);

return parsedResult["returnObj"].ToString();

 

Tried below way but Blazor is not supporting: 

 

string response;

WebRequest webRequest = WebRequest.Create($"{userContext.ServerAddress}/Erp.BO.ConfigurationRuntimeSvc/{apiName}");

webRequest.Method = "POST";

webRequest.Headers.Add("Authorization", "Basic " + userContext.Token);

webRequest.ContentType = "application/json";

 

// Create POST data and convert it to a byte array.

var json = JsonConvert.SerializeObject(request);

 

using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))

{

streamWriter.Write(json);

streamWriter.Flush();

}

 

var httpResponse = (HttpWebResponse)webRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))

{

response = streamReader.ReadToEnd();

}

 

var parsedResult = JObject.Parse(response);

return parsedResult["returnObj"].ToString();

Please provide a solution

  • 0

    I'm not sure why you'd want to block the UI thread, but this link might provide some ideas for running the asynchronous operation prior to rendering: https://github.com/dotnet/aspnetcore/issues/16217

    Posted 3 years ago by selliott
  • 0

    Thank you Selliott. I have a scenario where I am using ref and out keywords. Will blazor supports in future?

    Posted 3 years ago by manikanta
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 3
An error has occurred. This application may no longer respond until reloaded. Reload 🗙