简体   繁体   中英

C# Make Async HTTP call

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

BeginGetResponse should work. However I suspect that your program is terminating before the request is actually sent.

What you actually need to do is wait for the response and handle it. To do that you need to have a callback.

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

However, YOU REALLY SHOULDN'T BE USING THE APM MODEL ANYMORE!!!

You should use 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();

You are also missing a bunch of using / .Dispose() methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM