enable cors in c# web api controller code example

Example 1: asp.net core allow all origins

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://example.com",
                                "http://www.contoso.com")
                                .AllowAnyHeader()
                                .AllowAnyMethod();
        });
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Example 2: enable cors asp.net mvc

Response.AppendHeader("Access-Control-Allow-Origin", "*");

Tags:

Misc Example