CORS
When you’re building a web application, it’s common to have a frontend (the part your users see and interact with in their browser) and a backend API (the part that handles the business logic and data). For security reasons, web browsers have a rule called the “Same-Origin Policy,” which prevents a web page from making requests to a different domain than the one that served the page. This is a great security feature, but it can get in the way when your frontend and backend are hosted on different domains.
This is where CORS (Cross-Origin Resource Sharing) comes in. It’s a mechanism that allows a server to tell a browser that it’s okay to accept requests from certain other domains. In SliceFlow, configuring CORS is a breeze, so you can keep your application secure while still allowing your frontend to communicate with your API.
To get started, you just need to enable the CORS functionality in your Program.cs
file with a single line of code:
builder ... .ConfigureCors() ...
Once enabled, you need to tell SliceFlow which domains are allowed to access your API. This is done in your appsettings.json
file. For a production environment, you should always list the specific domains that you trust. For example, if your frontend is hosted at https://frontend.com
, you would configure it like this:
{ "Cors": { "AllowedOrigins": [ "https://frontend.com", "https://app.example.com" ] }}
During development, it can be convenient to allow requests from any domain. You can do this by using a wildcard (*
) in your configuration:
{ "Cors": { "AllowedOrigins": ["*"] }}
Warning: Using wildcard origins (
["*"]
) should only be used in development environments. In production, always specify explicit allowed origins for security.
Behind the scenes, SliceFlow automatically applies the correct CORS policy based on your configuration. When it sees the wildcard, it allows any origin; otherwise, it restricts access to the origins you’ve specified. By default, all HTTP headers and methods are allowed, which is what you’ll need in most cases.
If you need to customize the CORS policy further, you can do so by modifying the /Configuration/Cors.cs
file. For more in-depth information about CORS, you can always refer to the official Microsoft documentation.