add cors headers to a http server in csharp

To add CORS headers to an HTTP server in C#, you need to add a middleware that intercepts incoming requests and adds the appropriate headers before passing them on to the actual request handler.

Here's an example of how to do this using the Microsoft.AspNetCore.Builder and Microsoft.AspNetCore.Http packages:

main.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseCors(builder => builder
            .WithOrigins("http://example.com") // Replace with your allowed origins
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.Run(async context =>
        {
            // Your request handling code goes here
        });
    }
}
451 chars
19 lines

The UseCors method adds the middleware that intercepts incoming requests and adds the necessary headers. Here, we're allowing any HTTP method and header, but restricting the allowed origin to "http://example.com" (replace this with your own allowed origins).

Make sure to include the Microsoft.AspNetCore.Cors package in your project to use the UseCors method.

related categories

gistlibby LogSnag