3

I've been working on a new mvc core application where I'm using core as my backend, and I'm using react as my front end.

I've started running into problems with cors where I am unable to post anything from my react fronted into my mvc core backend. Looking into the documentation has not been very helpful and even taking a "scorched earth" approach by allowing everything:

services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });

isn't helping either and now I've no idea what is really happening other than my post requests are being rejected.

My action looks as follows:

    [HttpPost("_api/admin/monitor-customer")]
    public IActionResult SetCustomerMonitor([FromBody]UpdateMonitor model){
        try
        {
            var customer = Customers.Single(c => c.CustomerId == model.Id);
            customer.IsMonitored = !customer.IsMonitored;

            _context.SaveChanges();

            return Json(new { success = true });
        } catch(Exception ex){
            _logger.LogDebug(ex.Message, null);
            return Json(new { success = false });
        }
    }

My post request from react is as follows:

updateCustomer = (e) => {
    var customerId = e.target.value;

    $.ajax({
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        url: "http://localhost:5000/_api/admin/monitor-customer",
        data: JSON.stringify({ Id: customerId }),
        dataType: "json"
        });
}

Also include is my Startup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment())
        {
            builder.AddUserSecrets();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }
    ILogger _logger;
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AlertContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultSqlite")));
        //services.AddDbContext<AlertContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<DbContext, AlertContext>();
        services.AddSingleton<IDmsService>(new DmsService());

        services.AddMvc();
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseCors(options => options.AllowAnyHeader());
        app.UseCors(options => options.AllowAnyMethod());
        app.UseCors(options => options.AllowAnyOrigin());

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
Marqueone
  • 1,165
  • 2
  • 14
  • 33

1 Answers1

3

Problem solved due to where core is enabled.

service.AddCors() must precede services.AdMvc() in the ConfigureServices methods, and the same holds true for the Configure() method. app.UseCors() must be called before app.UseMvc()

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AlertContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultSqlite")));
        //services.AddDbContext<AlertContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<DbContext, AlertContext>();
        services.AddSingleton<IDmsService>(new DmsService());

        // Add service and create Policy with options
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials() );
        });

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        // global policy - assign here or on each controller
        app.UseCors("CorsPolicy");

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
Marqueone
  • 1,165
  • 2
  • 14
  • 33