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

Azure Function调用HttpWebRequest触发Socket权限禁止错误求助

解决HttpWebRequest调用本地接口时的Socket权限错误

我为实现可扩展性搭建了Azure Function用于批量上传图片,流程为:前端通过Ajax调用该Azure Function,Function将图片上传至Wasabi存储,上传完成后通过HttpWebRequest调用本地后端接口https://localhost:57028/Photo/UploadImages,代码如下:

var uploadImagesURL = "https://localhost:57028/Photo/UploadImages?albumId="+ albumId;
cookieString = parsedFormBody.Result.GetParameterValue("Cookie");

HttpWebRequest uploadImageWebRequest = (HttpWebRequest)WebRequest.Create(uploadImagesURL);
uploadImageWebRequest.Method = "POST";
var cookies = new CookieContainer();
string[] cookiePairs = cookieString.Split(';');
foreach (string cookiePair in cookiePairs)
{
    string[] keyValue = cookiePair.Trim().Split('=');
    if (keyValue.Length == 2)
    {
        string cookieName = keyValue[0];
        string cookieValue = keyValue[1];
        var cookie = new Cookie(cookieName, cookieValue)
        {
            Domain = "localhost"
        };
        cookies.Add(cookie);
    }
}
uploadImageWebRequest.CookieContainer = cookies;                                  
HttpWebResponse uploadImageWebResponse = (HttpWebResponse)uploadImageWebRequest.GetResponse();

执行(HttpWebResponse)uploadImageWebRequest.GetResponse();时触发错误:

System.Net.WebException: 尝试以一种访问权限不允许的方式访问套接字。


可能的解决方法

  • 检查端口占用:用命令netstat -ano | findstr :57028确认57028端口是否被其他进程占用,若占用则更换端口或终止占用进程。
  • 调整本地网络权限:Azure Function本地运行时可能受防火墙限制,尝试临时关闭防火墙测试,或在防火墙中添加Azure Function运行进程的出站规则,允许其访问localhost:57028。
  • 替换为HttpClientAPI:HttpWebRequest是较旧的网络请求API,改用HttpClient兼容性更好,示例代码:
var uploadImagesURL = $"https://localhost:57028/Photo/UploadImages?albumId={albumId}";
cookieString = parsedFormBody.Result.GetParameterValue("Cookie");

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, uploadImagesURL);
    request.Headers.Add("Cookie", cookieString);
    
    var response = await httpClient.SendAsync(request);
    response.EnsureSuccessStatusCode();
}
  • 确认后端服务监听配置:检查本地后端服务是否正确绑定到localhost,比如ASP.NET Core应用需在Program.cs中配置允许外部进程访问的监听地址(如ListenAnyIP)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:33:21