繁体   English   中英

C#进行异步HTTP调用

[英]C# Make Async HTTP call

我希望我的网站能够调用URL,就是这样。 我不需要等待回复。 我的ASP.Net项目之前使用的是webRequest.BeginGetResponse(null,requestState),但最近停止了工作。 不会抛出任何错误,但我已确认永远不会调用该URL。

当我使用webRequest.GetResponse()时,URL会被调用,但这种方法不是异步的,我需要它。

这是我的代码,任何可能出错的想法?

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 = "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()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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