You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET部署学校服务器后Post获取Token遇连接超时问题

问题描述

我用ASP.NET编写了一个调用第三方登录API的网页,在个人服务器上运行正常,但部署至学校服务器后,通过Post请求获取Token时出现以下错误:

Server Error in '/classMeeting' Application. A connection attempt failed because the connecting party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:
System.Net.Sockets.SocketException:
A connection attempt failed because the connected party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Source Error:
An unhandled exception was generated during the execution of the current webrequest. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +309
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +633
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +708
System.Net.HttpWebRequest.GetRequestStream() +21
classMeeting.index.GetAccess_token(String code, String client_id, String redirect_uri, String client_secret) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:130 classMeeting.index.readyLogin() in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:32
classMeeting.index.Page_Load(Object sender, EventArgs e) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:25
System.Web.UI.Control.OnLoad(EventArgs e) +109
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3321

对应的核心代码:

public static string GetAccess_token(string code, string client_id, string redirect_uri, string client_secret)
{
    var url = "https://openapi.yiban.cn/oauth/access_token";

    byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", client_id, client_secret, code, redirect_uri));

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
    webRequest.Method = "Post";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentLength = byteArray.Length;

    ServicePointManager.DefaultConnectionLimit = 50;

    Stream newStream = webRequest.GetRequestStream();

    newStream.Write(byteArray, 0, byteArray.Length);
    newStream.Close();

    HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

    StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);

    return php.ReadToEnd();
}
修复方案
  • 排查学校服务器网络限制:学校服务器通常有防火墙出站规则,大概率阻断了对112.65.235.59:443的访问。联系学校运维人员,申请将https://openapi.yiban.cn域名或对应IP端口加入白名单。
  • 配置代理服务器:如果学校网络必须通过代理访问外部资源,给HttpWebRequest添加代理配置:
    // 替换为学校实际代理地址和端口
    webRequest.Proxy = new WebProxy("http://school-proxy:8080");
    // 若代理需要认证,添加以下代码
    webRequest.Proxy.Credentials = new NetworkCredential("proxy-username", "proxy-password");
    
  • 指定TLS版本:旧版本.NET默认TLS版本较低,第三方API可能不兼容。在创建请求前添加:
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
    
  • 设置请求超时:学校网络延迟较高时,增加超时时间避免连接中断:
    webRequest.Timeout = 15000; // 15秒超时
    webRequest.ReadWriteTimeout = 15000;
    
  • 完善异常处理和资源释放:原代码未做异常捕获和资源自动释放,优化后便于排查问题:
    public static string GetAccess_token(string code, string client_id, string redirect_uri, string client_secret)
    {
        try
        {
            var url = "https://openapi.yiban.cn/oauth/access_token";
            var postData = string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", 
                                        client_id, client_secret, code, redirect_uri);
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    
            // 指定TLS版本
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
            ServicePointManager.DefaultConnectionLimit = 50;
    
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
            webRequest.Method = "Post";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            webRequest.Timeout = 15000;
            webRequest.ReadWriteTimeout = 15000;
    
            // 代理配置(按需启用)
            // webRequest.Proxy = new WebProxy("http://school-proxy:8080");
            // webRequest.Proxy.Credentials = new NetworkCredential("user", "pass");
    
            // 使用using自动释放资源
            using (Stream newStream = webRequest.GetRequestStream())
            {
                newStream.Write(byteArray, 0, byteArray.Length);
            }
    
            using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
        catch (Exception ex)
        {
            // 记录详细错误日志,或返回错误信息用于排查
            return $"请求失败: {ex.Message}\n堆栈信息: {ex.StackTrace}";
        }
    }
    
  • 验证网络连通性:在学校服务器上执行以下命令,确认网络层面是否能连通目标地址:
    ping openapi.yiban.cn
    telnet 112.65.235.59 443
    
    如果telnet失败,说明网络存在明确阻断,需优先联系运维解决。

内容的提问来源于stack exchange,提问作者user21033085

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 11:50:23