ASP.NET Core – True Ultimate Guide
Section 28: Angular and CORS
CORS in ASP.NET Core Web API
Cross-Origin Resource Sharing (CORS) is a feature that allows or restricts resources on a web server based on the origin of the request. In the context of an Angular application running on localhost:4200, you’ll need to configure CORS in your ASP.NET Core Web API to allow requests from this origin.
Overview of CORS
CORS enables web servers to specify which origins are allowed to access their resources. Proper CORS configuration ensures that your API can be accessed securely by client applications hosted on different origins.
Configuring CORS in ASP.NET Core Using Program.cs
1. Install Required Package
No additional package is needed as CORS support is built into ASP.NET Core.
2. Configure CORS in Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Add CORS services and configure policies
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAngularLocalhost",
builder =>
{
builder.WithOrigins("http://localhost:4200") // Allow Angular's localhost
.AllowAnyMethod() // Allow any HTTP method (GET, POST, etc.)
.AllowAnyHeader(); // Allow any headers
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
// Use CORS policy
app.UseCors("AllowAngularLocalhost");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();3. Understanding the Configuration
AddCorsMethod: Registers CORS services and defines policies.AddPolicyMethod: Creates a CORS policy named “AllowAngularLocalhost”.UseCorsMethod: Applies the defined CORS policy. It must be called beforeUseRoutingorUseEndpoints.
4. More Detailed CORS Policies
Restrictive CORS Policy:
builder.Services.AddCors(options =>
{
options.AddPolicy("RestrictedPolicy",
builder =>
{
builder.WithOrigins("https://specificdomain.com") // Allow only specific domain
.WithMethods("GET", "POST") // Allow only GET and POST methods
.WithHeaders("Authorization", "Content-Type"); // Allow specific headers
});
});Testing CORS Configuration
Example Angular Service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://localhost:5001/api/products';
constructor(private http: HttpClient) { }
getProducts() {
return this.http.get(this.apiUrl);
}
}Example Angular Component
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {
products: any[] = [];
constructor(private apiService: ApiService) { }
ngOnInit() {
this.apiService.getProducts().subscribe(data => {
this.products = data;
});
}
}Key Points to Remember
- CORS: Controls cross-origin requests to your API from different domains.
- Configuration: Set up CORS in
Program.csusingAddCorsandUseCorsmethods. - Origins: Allow specific domains like
localhost:4200to access your API. - Testing: Use browser developer tools to verify the presence and correctness of CORS headers.
- Policies: Customize CORS policies based on your application’s needs.