2016-11-21 144 views
2

我一直在研究一个新的mvc核心应用程序,我使用核心作为我的后端,并且使用react作为我的前端。asp.net核心mvc cors请求被拒绝

我已经开始遇到与cors有关的问题,因为我无法发布任何来自我的反应前端的内容到我的mvc核心后端。展望文件一直没有很大的帮助,甚至采取“焦土”的做法,允许一切:

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

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

没有任何帮助,现在我不知道究竟发生什么事其他比我的职位要求正在被拒绝。

我的动作看起来如下:

[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 }); 
     } 
    } 

从反应我的POST请求如下:

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" 
     }); 
} 

也包括我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?}"); 
     }); 
    } 
} 

回答

2

问题解决了因到启用核心的位置。

service.AddCors()必须在ConfigureServices方法中的services.AdMvc()之前,对于Configure()方法也是如此。 app.UseCors()必须在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?}"); 
     }); 
    }