我想在Blazor中同步调用API,但它不起作用。有没有办法同步调用API。请查找以下代码。
当前使用异步调用,如下所述:
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();
尝试了以下方式,但Blazor不支持:
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();
请提供解决方案
不知道这是否对你有帮助,但不久前在Github:上也提出了类似的问题
https://github.com/dotnet/aspnetcore/issues/16217
编辑:
文章摘要:
基本上,您不应该进行同步Http调用。首选选项:var result = await HttpClient.GetJsonAsync<T>(myUrl);
如果你真的想同步,这就是解决方案:
如果需要,可以在启动渲染器之前运行异步操作。例如,
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"); }); }
这是首选的解决方案,而不是试图阻止UI线程(浏览器不允许-他们会说选项卡崩溃了如果您正在阻塞UI线程(。