Register Log in

How to do synchronous calling of HttpClient in Blazor

Posted 16 days ago by manikanta
Edited 16 days 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

Post a Reply

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