C# WebResponse 調用GetResponse()方法時報錯:基礎鏈接已經關閉: 鏈接被意外關閉。

今天在弄一個登錄方法時,因爲請求的是測試服務器,要訪問接口的登錄方法,可是在請求過程當中, html

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);api

 WebResponse response = request.GetResponse();;緩存

response 請求報錯:基礎鏈接已經關閉: 鏈接被意外關閉。用postman請求登錄方法報錯以下:服務器

從字表意思是接口方法不容許方法,鏈接打不開。postman也沒法請求。可參考https://blog.csdn.net/jiangyu1013/article/details/82120052app

若是postman仍是請求不到,請看以下緣由:post

針對這個問題,有如下幾個可能:測試

1:在請求時加入參數限制,類如:url

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = 120 * 1000;
request.AllowAutoRedirect = true;
request.KeepAlive = true;
request.ContentType = contentType;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CertificateValidation);spa

2:(個人問題也是這個緣由)在訪問接口時,本地host文件沒有配置相關信息,可參考https://jingyan.baidu.com/article/fedf073754695735ac89772c.html.net

訪問路徑C:\Windows\System32\drivers\etc打開hosts文件【要以管理員打開,否則不餓能保存更改的內容】,在最後一行增長你訪問的接口配置信息,類如:

192.168.0.XXX   api.XXXXX.com就是你訪問的接口URL

# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
192.168.0.XXX   api.XXXXX.com

保存便可。再次運行項目,驚喜發現終於訪問成功!!

 

 

因爲有時候須要在局域網訪問項目,這裏介紹VS怎樣在局域網訪問項目:【如對此不敢興趣,爲節省你的寶貴時間,可忽略哦~】

1. 打開項目目錄下的.vs目錄, 修改applicationhost.config文件中的內容

2:【192.168.0.110是你的電腦的IP,可經過cmd ipconfig查看本機IP】

          <!--找到項目名-->

         < site  name="muTian.sysAdmin.UI.Portal" id="2">
             < application  path="/" applicationPool="Clr4IntegratedAppPool">
                 < virtualDirectory  path="/" physicalPath="D:\CsharpProject\muTian.sysAdmin\muTian.sysAdmin.UI.Portal" />
             </ application >
             < bindings >
                     <!--這一行是默認就有的-->
                 < binding  protocol="http" bindingInformation="*:10829:localhost" />
                 <!--這一行是增長的-->
                     <binding protocol="http" bindingInformation="*:10829:192.168.0.110" />
             </ bindings >
         </ site >      

3:打開cmd【注意以管理員打開】【10829是你的項目端口號,可在VS裏面右鍵-->>屬性查看】

執行 netsh http add urlacl url=http://192.168.0.110:59961/ user=everyone

此上下文中的命令:
show cacheparam - 顯示 HTTP 服務的緩存參數。
show cachestate - 列出緩存的 URI 資源及其相關屬性。
show iplisten - 顯示 IP 偵聽列表中的全部 IP 地址。
show servicestate - 顯示 HTTP 服務快照。
show setting - 顯示服務的設置值。
show sslcert - 顯示 SSL 證書綁定。
show timeout - 顯示服務的超時值。
show urlacl - 顯示 URL 命名空間保留項。

從新編譯運行項目,記得要以管理員省份打開VS,否則會出現503狀態碼的錯誤

至此,關於請求問題介紹完成,若有問題,可評論留言!!

 

原文出處:https://www.cnblogs.com/fengyulv/p/11824369.html

相關文章
相關標籤/搜索