Why does HttpClient only allow Async calls? WITH#

So, apparently, HttpClient only allows Asnyc calls?

Of course, you can call ".Result" like this:

public ActionResult Index()
{


            var someImportantData = httpClient.ReadAsStringAsync().Result;  // Aparently I shouldn't do this according to the article.
            // or    
            var someImportantData = Task.Run(() => Client.PostAsync()).Result;

            Return View( new MyViewModel(someImportantData));
}

to make it synchronous, but this is apparently very dangerous and should be avoided as it causes a dead end, as described here.

So what are my options for synchronous queries? Am I going to use the power of the old HttpWebRequest? In my specific MVC action, I want the call to be synchronous, since I don't want to return the page until I collect the data from the calm api call.

+4
source share
2

API-, . await .

public async Task<ActionResult> Index() {
    var someImportantData = await httpClient.ReadAsStringAsync(...);
    return View(new MyViewModel(someImportantData));
}

, (.. ) API, .

, API. .

.Result , .

. .

+3

.Result . await :

:

public async Task<ActionResult> Index()
{
      var someImportantData = await httpClient.ReadAsStringAsync().ConfigureAwait(false); 
      return View( new MyViewModel(someImportantData)); // This line will not be called until previous line is completed.
}

ConfigureAwait(false) . ASP.NET Core, , . .

0

Source: https://habr.com/ru/post/1683848/


All Articles