To add CORS headers to an HTTP server with a specific origin in C#, you need to create a middleware component that checks for incoming requests, and if it matches your desired origin, add the required headers to its response.
Below is an example of how to achieve that:
main.cs1066 chars34 lines
To use this middleware component, add a call to the extension method UseMiddleware()
in the Configure()
method of your Startup class:
main.cs515 chars20 lines
In the example above, the CorsMiddleware
component takes two arguments: next
and allowedOrigin
. next
is a reference to the next middleware component in the pipeline, while allowedOrigin
is the origin that you want to allow to access your resources. If a request matches the allowed origin, the middleware will add the required headers to its response.
You can also modify the code to allow multiple origins by changing the allowedOrigin
parameter to an array of strings, and then checking whether the incoming request matches any of the allowed origins.
gistlibby LogSnag