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

To add CORS headers to a HTTP server with a specific origin and methods in C#, you can use the UseCors method from the ASP.NET Core middleware.

Here's an example of how to add CORS headers with a specific origin and methods:

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

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins("https://example.com")
                    .WithMethods("GET", "POST")
                    .AllowCredentials();
            });
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("CorsPolicy");

        // ... Other middleware here
    }
}
613 chars
26 lines

In this example, we're adding a CORS policy with the specific origin "https://example.com" and the allowed methods "GET" and "POST". We're also allowing credentials to be sent with the request by calling AllowCredentials().

The CORS middleware is then added to the pipeline using the UseCors method with the name of our policy "CorsPolicy".

Note that this example is for ASP.NET Core, but you can also add CORS headers to other types of servers by modifying the middleware or by using a third-party library.

related categories

gistlibby LogSnag