liveBook · Manning

CORS middleware

As explained in Building Web APIs with ASP.NET Core

CORS middleware is an HTTP pipeline component that applies cross-origin request policies to web API requests and responses.

CORS middleware applies a cross-origin policy across an ASP.NET Core app. It is the simplest choice when the board-game API should use the same default policy for its controllers and Minimal API endpoints. section 3.1.1

// ...
 
app.UseCors();
 
app.UseAuthorization();
 
// ...

Add `app.UseCors()` in `Program.cs` before `app.UseAuthorization()`. Middleware runs in the order it is added, so placement matters for authorization and endpoints. section 3.1.1

The default policy can allow origins specified by `AllowedOrigins`. Although `app.UseCors("AnyOrigin")` would apply the named policy globally, reserve an all-origins policy for cases that need it; endpoint routing or `[EnableCors]` can target particular endpoints instead. If credentials such as cookies or authorization headers are allowed, the origin cannot be `*`: both client and server must acknowledge credentialed requests and specify an origin. section 3.1.1

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Shows policy registration and middleware placement, then contrasts global application with endpoint-level alternatives.
Examples
Uses `Program.cs` configurations for a default policy, an `AnyOrigin` policy, and an `AllowedOrigins` setting.
What you can do after
Operate/configure it by placing `app.UseCors()` before authorization and choosing between default and named policies.
How it connects
Connects CORS middleware to same-origin policy, endpoint routing, authorization middleware, and Cross-Site Request Forgery.

Also explained in

Compare how 2 books explain CORS middleware →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.