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

Angular 19与.NET Framework Web API集成的CORS问题求助

Angular 19 + ASP.NET Web API(.NET Framework)CORS问题排查与解决

问题现象

前端从http://localhost:4200向后端https://localhost:44377/api/auth/login发起POST请求时,触发CORS错误:

"Access to XMLHttpRequest at 'https://localhost:44377/api/auth/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

环境信息

  • Angular 19应用:http://localhost:4200
  • ASP.NET Web API(.NET Framework):https://localhost:44377

已执行操作

  • 在控制器及Action上添加EnableCors属性,同时在WebApiConfig.cs中全局启用CORS
  • 安装Microsoft.AspNet.WebApi.Cors NuGet包
  • 配置EnableCors属性允许所有源、方法、请求头(origins: "*", methods: "*", headers: "*")

代码片段

ASP.NET Web API 代码

[EnableCors(origins: "http://localhost:4200/login", headers: "*", methods: "*")]
public class AuthController : ApiController
{
    private readonly AuthService _authService = new AuthService();
    
    [HttpPost]
    [EnableCors(origins: "*", methods: "*", headers: "*")]
    [Route("api/auth/login")]
    public IHttpActionResult Login([FromUri] LoginRequest request)
    {
        if (_authService.ValidateUser(request.username, request.password))
        {
            var token = _authService.GenerateToken(request.username);
            return Ok(new { token });
        }

        return Unauthorized();
    }
}

public class LoginRequest
{
    public string username { get; set; }
    public string password { get; set; }
}

Angular 代码

import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [FormsModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {
  loginObj : any = {
    username: "",
    password: "",
  };
  token: string | null = null;
  errorMessage: string = '';
  http= inject(HttpClient);

  onlogin() {
    debugger;
    this.http.post('https://localhost:44377/api/auth/login', this.loginObj).subscribe((res: any) => {
      if (res.result) {
        alert("login sucess")
      } else {
        alert(res.message)
      }
    })
  }
}

export class Login {
  username: string;
  password: string;
  constructor() {
    this.username = '';
    this.password = '';
  }
}

排查与解决建议

1. 修正WebApiConfig.cs的CORS注册

确保Register方法中正确启用全局CORS,代码示例:

public static void Register(HttpConfiguration config)
{
    // 全局启用CORS
    var corsAttr = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(corsAttr);

    // 路由配置
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

如果同时使用全局和局部EnableCors属性,局部配置会覆盖全局,但必须保证全局CORS已正确注册。

2. 修正控制器上的源地址配置

控制器类上的EnableCors指定了http://localhost:4200/login,这是错误的——CORS的源应该是前端应用的根地址http://localhost:4200,而非具体路由。建议删除控制器类上的EnableCors属性,仅保留Action上的配置,或统一设置正确的源。

3. 修正参数绑定方式

Angular通过POST请求体发送登录数据,但后端Action使用[FromUri]从URL读取参数,这会导致请求体无法解析,同时可能导致预检OPTIONS请求处理失败。将[FromUri]改为[FromBody]:

public IHttpActionResult Login([FromBody] LoginRequest request)

这是核心问题之一,POST请求的参数必须从请求体读取,否则后端无法正确响应预检请求,进而触发CORS错误。

4. 检查OPTIONS请求响应

打开浏览器开发者工具(Network标签),查看OPTIONS预检请求的响应头,确认是否包含Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers这些必要头。如果缺失,说明CORS配置未生效。

5. 排查IIS/IIS Express配置

检查项目的web.config,确认<system.webServer>节点中没有自定义的HTTP头干扰CORS响应:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <!-- 避免添加与CORS冲突的Origin头 -->
        </customHeaders>
    </httpProtocol>
</system.webServer>

6. 重新安装NuGet包

尝试卸载Microsoft.AspNet.WebApi.Cors,清理项目后重新安装,确保包版本与Web API版本兼容。

内容的提问来源于stack exchange,提问作者Manel Ben Sayari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:06:05