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

Angular应用调用Azure上.NET后端随机出现504及CORS问题求助

Angular调用.NET后端随机出现504及CORS错误排查求助

技术栈

  • 后端:.NET 8
  • 前端:Angular 16+(启用服务器端渲染与渐进式Web应用)
  • 授权方式:JWT
  • 数据库:PostgreSQL
  • 部署环境:前后端均部署在Linux生产计划的Azure App Service中

问题的随机性表现

  1. 同一接口在同一天不同时间,同一/不同用户调用时可能正常,也可能报错
  2. 部分用户出现504错误时,后端仍在正常处理大量其他请求
  3. 用户有时遇到504错误,有时会触发如下CORS报错:
    Access to fetch at 'https://my-backend-server/endpoint' from origin 'https://my-frontend-app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

已尝试的排查方案

  • .NET端:将CORS配置修改为.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
  • .NET端:在CORS策略中添加.SetIsOriginAllowed((host) => true)
  • Azure端:升级App Service的规模
  • Angular端:在注入JWT的HttpInterceptor中添加RxJS超时配置:return next.handle(request).pipe(timeout(this._defaultTimeout));
  • Angular端:在两端App Service中添加ApplicationInsights以排查错误(现已确认每日大量用户遇到该问题)
  • Angular端:优化<meta http-equiv="Content-Security-Policy"标签,将所有外部调用纳入对应规则
  • Azure端:禁用两端App Service的CORS配置(导致应用崩溃)

目前未发现失败请求的规律:请求类型(GET/POST)、是否带鉴权、时段(日间或低峰时段约22点)、涉及的控制器等均无固定模式。

补充配置

.NET Program.cs中的CORS配置

// Defines CORS policy
builder.Services.AddCors(options =>
{
    options.AddPolicy(CorsPolicyName,
        builder =>
        {
            builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed((host) => true);
        });
});
...
var app = builder.Build();

app.UseCustomExceptionHandler();
app.UseHttpsRedirection();
app.UseCors(CorsPolicyName);
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
...

为排查是否由CORS导致,已简化CORS策略以允许所有请求,此前使用的是.WithOrigins([.. AllowedOrigins]),其中AllowedOrigins是包含前端App Service源、Azure Functions及合作方地址的List<string>。

Azure中的CORS配置

Azure App Service的CORS配置界面中,已添加的所有URL均匹配前端App Service或合作方地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 00:55:56