C#进行异步HTTP调用
我想让我的网站打电话到一个网址,就是这样。我不需要等待回复。我的ASP.Net项目以前使用webRequest.BeginGetResponse(null,requestState),但最近已停止工作。没有抛出错误,但我已确认从未调用URL 当我使用webRequest.GetResponse()时,确实会调用URL,但这种方法不是异步的,我需要它是异步的 这是我的代码,有什么想法可能是错误的吗C#进行异步HTTP调用,c#,asp.net,asynchronous,C#,Asp.net,Asynchronous,我想让我的网站打电话到一个网址,就是这样。我不需要等待回复。我的ASP.Net项目以前使用webRequest.BeginGetResponse(null,requestState),但最近已停止工作。没有抛出错误,但我已确认从未调用URL 当我使用webRequest.GetResponse()时,确实会调用URL,但这种方法不是异步的,我需要它是异步的 这是我的代码,有什么想法可能是错误的吗 HttpWebRequest webRequest = (HttpWebRequest)WebReq
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "GET";
NetworkCredential nc = new NetworkCredential("theUsername", "thePassword");
webRequest.Credentials = nc;
webRequest.PreAuthenticate = true;
RequestState rs = new RequestState();
rs.Request = webRequest;
IAsyncResult r = (IAsyncResult)webRequest.BeginGetResponse(null, rs);
这是可以工作但不是异步的代码
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "GET";
NetworkCredential nc = new NetworkCredential("theUsername", "thePassword");
webRequest.Credentials = nc;
webRequest.PreAuthenticate = true;
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
BeginGetResponse
应该可以工作。但是,我怀疑您的程序在实际发送请求之前终止
实际上,您需要做的是等待响应并处理它。要做到这一点,您需要有一个回调
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = WebRequestMethods.Http.Get;
NetworkCredential nc = new NetworkCredential("theUsername", "thePassword");
webRequest.Credentials = nc;
webRequest.PreAuthenticate = true;
RequestState rs = new RequestState();
rs.Request = webRequest;
WebResponse response;
IAsyncResult r = (IAsyncResult)webRequest.BeginGetResponse(x => response = webRequest.EndGetResponse(x), rs);
Thread.Sleep(10000);
然而,你真的不应该再使用APM模型了
您应该使用async/await
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = WebRequestMethods.Http.Get;
NetworkCredential nc = new NetworkCredential("theUsername", "thePassword");
webRequest.Credentials = nc;
webRequest.PreAuthenticate = true;
RequestState rs = new RequestState();
rs.Request = webRequest;
WebResponse response = await webRequest.GetResponseAsync();
您还缺少一组使用/.Dispose()
方法的