如何在Blazor中同步调用HttpClient

问题描述

我想在Blazor中同步调用API,但无法正常工作。有没有一种方法可以同步调用API。请找到以下代码

当前正在使用异步调用,如下所述:

<div>
 <div id="nav">
  <ul>
    <li>
      <div class="search-container">
        <form action="/action_page.PHP">
            <input type="text" placeholder="Search Quora" name="search" onfocus="quo(this)">
        </form>
        </div>
    </li>
    <li>
      <a href="#user"><i class="fas fa-user-circle fa-lg"></i></a>
    </li>
    <li>
      <button class="add">Add Question</button>
    </li>
  </ul>
 </div>
 <div class="content">
  <div id="left">
    <h2>Column 1</h2>
    <p>Some text..</p>
  </div>
  <div id="middle">
    <h2>Column 2</h2>
    <p>By way of precaution,when all was complete De Rozier made a few short captive excursions,the balloon being fastened to earth by a rope. But all proving satisfactory,he decided to hazard a right away trip on the 21st of November 1783,when he was also to be accompanied by an equally courageous fellow-countryman,the Marquis dArlandes. It would be difficult to conceive a more daring and perilous enterprise than these two brave frenchmen set themselves. They were to venture,by an untried way,into unkNown realms where no mortal had been before; they were to entrust their lives to a frail craft whose capabilities had never yet been tested,and at a giddy height they were to soar aloft with an open fire,which at any moment might set light to the inflammable balloon and hurl them to destruction.
    t all proving satisfactory,into unkNown realms where no mortal had been before; they were
    t all proving satisfactory,into unkNown realms where no mortal had been before; they were
    
    </p>
 </div>
  <div id="right">
    <h2>Column 3</h2>
    <p>Some text..</p>
  </div>
 </div>
</div>

尝试以下方法,但Blazor不支持

    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();

请提供解决方

解决方法

不知道这是否对您有帮助,但是不久前在Github上问了一个类似的问题:

https://github.com/dotnet/aspnetcore/issues/16217

编辑:

文章摘要:

基本上,您不应该执行同步Http调用。 首选选项:Player.

如果您真的想进行同步,这是解决方案:

如果需要,可以在启动渲染器之前运行异步操作。例如,

class Player:

    nPlayers = 0
    player_list = []

    def __init__ (self):
        self.n = Player.nPlayers + 1
        Player.nPlayers += 1
        Player.player_list.append(self)

这是首选解决方案,而不是尝试阻止UI 线程(浏览器不允许的-他们会说该标签页已崩溃 如果您要阻止UI线程)。