C# Make Async HTTP call

时间:2016-04-01 01:26:34

标签: c# asp.net asynchronous

I want my website to make a call to a URL, and that's it. I don't need it to wait for a response. My ASP.Net project was previously using webRequest.BeginGetResponse(null, requestState) but has recently stopped working. No errors are thrown, but I have confirmed that the URL is never called.

When I use webRequest.GetResponse() the URL does get called but this approach is not asynchronous, which I need it to be.

Here is my code, any ideas of what could be wrong?

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

This is the code that works but is not asynchronous..

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

1 个答案:

答案 0 :(得分:4)

BeginGetResponse应该有效。但是我怀疑你的程序在实际发送请求之前就已经终止了。

您实际需要做的是等待响应并处理它。为此,您需要进行回调。

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

您也缺少一堆using / .Dispose()方法。