how to configure cors in c# in csharp

Here's an example of how to configure CORS in C#:

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

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("MyCorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            });
        });
 
        // other services configuration
    }
 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("MyCorsPolicy");
 
        // other middleware configuration
    }
}
667 chars
28 lines

In this example, we're adding a CORS policy named "MyCorsPolicy" that allows any origin, method, and header. We're then using this policy in the Configure method to allow CORS requests for all incoming requests. You can customize the policy as needed, such as specifying specific origins or methods that are allowed.

related categories

gistlibby LogSnag