Home > Software design >  how to enable CORS in MVC .Net 5?
how to enable CORS in MVC .Net 5?

Time:05-01

I have a simple action in the front-end(javascript), that returns some JSON. here is the code sample,

function DiacritizeText() {
    var text = $("#Paragraph").val()
    var api_key = "Api_Key";
    var i;
    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://farasa.qcri.org/webapi/segmentation/",
        "method": "POST",
        "headers": { "content-type": "application/json", "cache-control": "no-cache", },
        "processData": false,
        "data": "{\"text\":"   "\""   text   "\", \"api_key\":"   "\""   api_key   "\"}",
    }
    $.ajax(settings).done(function (response) {
        console.log(response);
        $("#Paragraph").text(JSON.parse(response).text);
    });
}

when I execute this function I got these errors

Access to XMLHttpRequest at 'https://farasa.qcri.org/webapi/segmentation/' from origin https://localhost:44377' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
POST https://farasa.qcri.org/webapi/segmentation/ net::ERR_FAILED 400

I have searched some recourses and most of them provided that the handling should be done at the API, but this is impossible as the API is not in our network I have to try to enable toe CORS from my side

1st attempt is to add the CORS in the Startup

public class Startup
    {
        readonly string allowSpecificOrigins = "_allowSpecificOrigins";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.WithOrigins("https://farasa.qcri.org/")
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        var ConnectionString = Configuration.GetConnectionString("EducationSystemDBContextConnection");

        services.AddDbContext<EducationSystemDBContext>(options => options.UseSqlServer(ConnectionString));


        var mapperConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MappingProfile());
        });

        IMapper mapper = mapperConfig.CreateMapper();
        services.AddSingleton(mapper);
        //services.AddAutoMapper(typeof(Startup));

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie("Cookies", options =>
        {
            options.LoginPath = "/User/Login";
            options.LogoutPath = "/User/Logout";
            options.AccessDeniedPath = "/User/AccessDenied";
            options.ReturnUrlParameter = "ReturnUrl";
        });

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            //app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //app.UseMvcWithDefaultRoute();
        app.UseRouting();
        app.UseCors("MyPolicy");
        
        app.UseCookiePolicy(new CookiePolicyOptions()
        {
            MinimumSameSitePolicy = SameSiteMode.Strict
        });

        app.UseAuthentication();
        app.UseAuthorization();
        
        //app.MapRazorPages();
        //app.MapDefaultControllerRoute();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

       
    }
}

2nd attempt since I faced the same issue in the ASP.Net Framework and I fixed it by adding in the web.config I thought it may go the same way in .Net core so I have added a web.config in the core MVC web app then added the as following

<system.webServer>
    <httpProtocol>
            <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

so, how can I handle the CORS from my core MVC web App?

CodePudding user response:

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

or

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

or you can add this to wor web.config file:

<system.webServer>

    <httpProtocol>

      <customHeaders>

        <clear />

        <add name="Access-Control-Allow-Origin" value="*" />

      </customHeaders>

    </httpProtocol>

if you want to enable CORS for web api, you need to add this to your web Api project's global.asax folder.

protected void Application_BeginRequest()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        }

CodePudding user response:

I wrote this Extention for adding to services and use on middleware

    public static class CorsSvcExtentions
{
    private const string  MyAllowSpecificOrigins = "nilesoftCors";
    public static IServiceCollection AddNileSvcCores(this IServiceCollection service,string origin)
    {

        service.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .WithOrigins(origin);
                                  builder
                                    .SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
                              });
        });
         
        return service;
    }

    public static void UseNileSvcCores(this IApplicationBuilder app)
    {
        app.UseCors(MyAllowSpecificOrigins);
    }
}

Startup Class

services.AddNileSvcCores("https://farasa.qcri.org/");

app.UseNileSvcCores();
  • Related