最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - CORS Issue Angular & .NET Project - Stack Overflow

programmeradmin6浏览0评论

I’m currently working on a project that involves integrating an Angular 19 frontend with an ASP.NET Web Application (.NET Framework) API backend, and I've run into a CORS issue.

When I try to make a request from the frontend (Angular) to the backend (ASP.NET Web API), I get the following error:

"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."

Here’s a brief overview of the setup:

My Angular application runs on http://localhost:4200.

My ASP.NET Web API runs on https://localhost:44377.

I don’t have a Program.cs or Startup.cs file in my project, as it's an ASP.NET Web Application (.NET Framework) project. I’ve followed the steps outlined in the official Microsoft documentation (here) to enable CORS, but the issue persists.

What I’ve tried so far:

  • Added the EnableCors attribute in the controller and enabled CORS globally in the WebApiConfig.cs file.
  • Installed the Microsoft.AspNet.WebApi.Cors package.
  • Used the EnableCors attribute with origins: "", methods: "", headers: "*".

Despite these steps, the issue persists. I’ve seen some similar cases online, but I’m still not sure what might be causing the problem. Would you be able to share any insights or suggestions that could help resolve this?

This my code in C# and Angular:

C# code:

 [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 TypeScript:

import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
//import { HttpClientModule } from '@angular/common/http';
@Component({
  selector: 'app-login',
  standalone: true, // Indique que c'est un composant autonome
  imports: [FormsModule],
  templateUrl: './loginponent.html',
  styleUrl: './loginponent.css'
})
export class LoginComponent {
  //loginObj: Login;
  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 = '';
  }
}

I’m currently working on a project that involves integrating an Angular 19 frontend with an ASP.NET Web Application (.NET Framework) API backend, and I've run into a CORS issue.

When I try to make a request from the frontend (Angular) to the backend (ASP.NET Web API), I get the following error:

"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."

Here’s a brief overview of the setup:

My Angular application runs on http://localhost:4200.

My ASP.NET Web API runs on https://localhost:44377.

I don’t have a Program.cs or Startup.cs file in my project, as it's an ASP.NET Web Application (.NET Framework) project. I’ve followed the steps outlined in the official Microsoft documentation (here) to enable CORS, but the issue persists.

What I’ve tried so far:

  • Added the EnableCors attribute in the controller and enabled CORS globally in the WebApiConfig.cs file.
  • Installed the Microsoft.AspNet.WebApi.Cors package.
  • Used the EnableCors attribute with origins: "", methods: "", headers: "*".

Despite these steps, the issue persists. I’ve seen some similar cases online, but I’m still not sure what might be causing the problem. Would you be able to share any insights or suggestions that could help resolve this?

This my code in C# and Angular:

C# code:

 [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 TypeScript:

import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
//import { HttpClientModule } from '@angular/common/http';
@Component({
  selector: 'app-login',
  standalone: true, // Indique que c'est un composant autonome
  imports: [FormsModule],
  templateUrl: './loginponent.html',
  styleUrl: './loginponent.css'
})
export class LoginComponent {
  //loginObj: Login;
  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 = '';
  }
}

Share Improve this question edited Mar 31 at 23:31 GoldenWRaft 234 bronze badges asked Mar 27 at 12:03 manel sayarimanel sayari 371 silver badge3 bronze badges 1
  • This question is similar to: XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Heretic Monkey Commented Mar 31 at 17:03
Add a comment  | 

3 Answers 3

Reset to default 0

You could try package Microsoft.AspNet.WebApi.Cors

the WebApiConfig.cs

var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);

// before
config.MapHttpAttributeRoutes();

Have you tried to set proxy config for Angular app?

Docs for proxy.config: https://angular.dev/tools/cli/serve#proxying-to-a-backend-server

An example of usage: https://dev.to/developersmill/angular-proxy-configuration-for-api-calls-130b

In your Program.cs file you should be able to set up the configuration for CORS calls when it's on the same machine

app.UseCors(cors => cors
    .AllowAnyMethod()
    .AllowAnyOrigin()
    .AllowAnyHeader());

To get your initial setup working, then later down the line you should be able to update your appsettings.json file to contain protections such as:

  "HttpSanitizationOptions": {
    "MethodWhitelist": "GET;POST",
    "StatusCodeWhitelist": "200;401;301"
  },
发布评论

评论列表(0)

  1. 暂无评论