Reputation: 39
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
Upvotes: 1
Views: 1909
Reputation: 571
Don´t know if that helps you, but a similar question was asked some time ago on Github:
https://github.com/dotnet/aspnetcore/issues/16217
Edit:
Summary of the article:
Basically you shouldn´t do a synchronous Http call.
Preferable option: var result = await HttpClient.GetJsonAsync<T>(myUrl);
This is the solution if you really want to do it synchronish:
You can run asynchronous operations before starting the renderer if you want to. For example,
static void Main(string[] args) { Task.Run(async () => { var serviceProvider = new BrowserServiceProvider(services => { // Add any custom services here }); // First run an async HTTP request var httpClient = serviceProvider.GetService<HttpClient>(); var data = await httpClient.GetStringAsync("/api/SampleData/WeatherForecasts"); Console.WriteLine("Fetched data: " + data); // Now the request is completed, start rendering the UI new BrowserRenderer(serviceProvider).AddComponent<App>("app"); }); }
This is the preferred solution, rather than attempting to block the UI thread (which browsers don't allow - they'll say the tab has crashed if you're blocking the UI thread).
Upvotes: 2