add cors headers to a http server with a specific origin in csharp

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.cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class CorsMiddleware
{
    private readonly RequestDelegate _next;
    private readonly string _allowedOrigin;

    public CorsMiddleware(RequestDelegate next, string allowedOrigin)
    {
        _next = next;
        _allowedOrigin = allowedOrigin;
    }

    public async Task Invoke(HttpContext context)
    {
        context.Response.Headers.Add("Access-Control-Allow-Origin", _allowedOrigin);
        context.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        if (context.Request.Method == "OPTIONS")
        {
            // Handle CORS preflight request
            context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            context.Response.Headers.Add("Access-Control-Max-Age", "86400");
            context.Response.StatusCode = StatusCodes.Status200OK;
            return;
        }

        // Call the next middleware component in the pipeline
        await _next(context);
    }
}

1066 chars
34 lines

To use this middleware component, add a call to the extension method UseMiddleware() in the Configure() method of your Startup class:

main.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add your services here
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Use the CORS middleware for a specific origin
        app.UseMiddleware<CorsMiddleware>("https://example.com");

        // Add your middleware components here
    }
}
515 chars
20 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