asp.net cors 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

public static void Register(HttpConfiguration config)
{
    var corsAttr = new EnableCorsAttribute("http://example.com", "*", "*");
    config.EnableCors(corsAttr);
}

Example 3: how to enable cors policy in web api

BY LOVE
To enable CORS policy in web api, You need to add this method in your Global.asax file of API project. i.e
        
        protected void Application_BeginRequest()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        }

Example 4: enable cors asp.net mvc

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

Example 5: enable cors asp.net mvc

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