使用POST方法在通用应用程序中发送登录数据

我正在使用Windowsapp store,我正在尝试发送登录名和密码值,这是我的代码:

try { string user = login.Text; string pass = password.Password; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "login=" + user + "&mdp=" + pass; byte[] data = encoding.GetBytes(postData); WebRequest request = WebRequest.Create("myURL/login.php"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Dispose(); WebResponse response = request.GetResponse(); stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); sr.Dispose(); stream.Dispose(); } catch (Exception ex) { ex.Message.ToString(); } 

我有很多这样的错误:

 'WebRequest' does not contain a definition for 'Content Length' and no extension method 'ContentLength' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing ?) 'WebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing? ) 'WebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing? ) 

我是通用Windows应用程序的新手,所以请您知道如何更正我的代码以将登录数据发送到服务器感谢您的帮助

正如您所注意到的,.NET Core中的WebRequest类与传统.NET略有不同。 首先,我建议您查看HttpClient类,它是UWP中用于处理HTTP的默认类。

如果要使用WebRequest,要设置Content-Length标头,请使用Headers属性:

 request.Headers["ContentLength"] = length; 

为了获取请求和响应流,您需要使用异步方法GetRequestStreamAsync和GetResponseAsync。 同步方法不可用。

毕竟你的代码看起来像这样:

 string user = login.Text; string user = login.Text; string pass = password.Password; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "login=" + user + "&mdp=" + pass; byte[] data = encoding.GetBytes(postData); WebRequest request = WebRequest.Create("myURL/login.php"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Headers["ContentLength"] = data.Length.ToString(); using (Stream stream = await request.GetRequestStreamAsync()) { stream.Write(data, 0, data.Length); } using (WebResponse response = await request.GetResponseAsync()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { // } } }