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

.NET Core 5 Angular应用VS运行时报SocketException连接被拒绝错误

问题场景

在Visual Studio中运行基于.NET Core 5开发的Angular应用时,页面提示请求处理发生未处理异常,核心错误堆栈如下:

An unhandled exception occurred while processing the request.
SocketException: No connection could be made because the target machine actively refused it.
System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)

HttpRequestException: No connection could be made because the target machine actively refused it. (localhost:53797)
System.Net.Http.ConnectHelper.ConnectAsync(Func<SocketsHttpConnectionContext, CancellationToken, ValueTask<Stream>> callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken)

HttpRequestException: Failed to proxy the request to http://localhost:53797/, because the request to the proxy target failed. Check that the proxy target server is running and accepting requests to http://localhost:53797/.

The underlying exception message was 'No connection could be made because the target machine actively refused it. (localhost:53797)'.Check the InnerException for more details.
Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task<Uri> baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s)
错误根因

这个错误是.NET Core内置的SPA开发代理转发请求失败导致的:开发模式下.NET后端不会直接处理前端静态资源请求,会把所有前端路由的请求转发给Angular CLI启动的本地开发服务器(也就是报错里的localhost:53797),连接被拒说明Angular前端开发服务根本没成功启动,或者启动后没监听对应端口,和后端业务代码没有直接关系。

排查解决步骤
  • 校验Node.js运行环境:打开终端执行node -v、npm -v,确认Node版本符合当前Angular版本的兼容要求(.NET 5配套的Angular 11/12版本对应Node 12/14长期支持版),未安装Node或者版本不匹配会直接导致Angular服务启动失败,安装对应版本Node后重启Visual Studio即可。
  • 手动恢复前端依赖:进入项目下存放Angular代码的ClientApp目录,执行npm install完整安装所有前端依赖,依赖缺失、安装不完整是Angular启动失败的最常见原因,依赖安装完成后再重新启动项目。
  • 检查开发环境配置:打开项目根目录下Properties/launchSettings.json,确认启动配置里的ASPNETCORE_ENVIRONMENT值为Development,非开发环境下.NET不会自动启动Angular开发服务;同时检查Startup.cs中的SPA配置,确认开发环境下UseSpa模块配置了自动执行npm start启动Angular服务,不要手动硬写错误的固定代理端口。
  • 查看前端启动的真实报错:启动项目时在Visual Studio的输出窗口,将日志来源切换为NPM,可以看到Angular CLI启动时的具体错误,常见问题包括端口被其他进程占用、npm脚本配置错误、Angular本地依赖版本冲突:
    • 如果是端口被占用,执行netstat -ano | findstr "53797"找到占用端口的进程ID,在任务管理器结束对应进程;也可以修改ClientApp/package.json里的start脚本,指定新的启动端口比如ng serve --port 53800,同步调整SPA代理的目标端口即可。
  • 手动预启动前端服务验证:先进入ClientApp目录手动执行npm start,等终端提示Angular服务启动完成、本地可以正常访问对应端口的Angular页面后,再启动.NET后端项目,此时代理可以直接连接已经启动的前端服务,不会触发连接拒绝错误。
  • 排查本地拦截规则:如果上述步骤都正常,检查本地防火墙、第三方安全软件是否拦截了localhost的本地回环端口访问,临时关闭安全软件验证,确认是拦截问题后给对应端口加本地访问白名单即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:18:13