[英]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.