如何使用aysnc转换HTTP的Web请求的异步请求

如何使用aysnc转换HTTP的Web请求的异步请求

本文介绍了如何使用aysnc转换HTTP的Web请求的异步请求,并等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有登录用户的简单的请求的功能。我刚刚了解aysnc方法(我是C#初学者),并看到了请求可以使用异步进行,并等待。但我有一个很难搞清楚如何转换现有的code。我读similar问题计算器上,但仍然没有能够使之与我的code工作。

I have a simple request function that logs a user in. I just learned about aysnc method (I am a C# beginner) and saw that requests can be made using async and await. But I am having a hard time figuring out how to convert my existing code. I read similar questions on stackoverflow but still haven't been able to make it work with my code.

public static string LogIn(string email, string password)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost");
    request.Method = "POST"
    request.ContentType = "application/json";
    request.CookieContainer = cookies;
    CredentialClass credentials = new CredentialClass();
    credentials.email = email
    credentials.password = password;
    var ser = new DataContractJsonSerializer(typeof(CredentialClass));
    ser.WriteObject(request.GetRequestStream(), credentials);
    var response = (HttpWebResponse)request.GetResponse();
    return (response.StatusCode.ToString());
}

任何建议我将如何使它工作?

Any suggestions on how would I make it work?

推荐答案

绝对最简单的方法就是更换的HttpWebRequest 的HttpClient

The absolute easiest way is to replace HttpWebRequest with HttpClient.

您还需要使用异步方法签名:

You'll also want to use an asynchronous method signature:

public static async Task<string> LogInAsync(string email, string password)

这篇关于如何使用aysnc转换HTTP的Web请求的异步请求,并等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:34