asp.net core mvc cors请求被拒绝[重复]

Posted

技术标签:

【中文标题】asp.net core mvc cors请求被拒绝[重复]【英文标题】:asp.net core mvc cors request denied [duplicate] 【发布时间】:2017-04-04 07:46:01 【问题描述】:

我一直在开发一个新的 mvc 核心应用程序,其中我使用核心作为我的后端,我使用反应作为我的前端。

我已经开始遇到 cors 问题,我无法从我的 react 前端发布任何内容到我的 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 );
        
    

我的react发帖请求如下:

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

【问题讨论】:

【参考方案1】:

由于启用了核心,问题已解决。

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

【讨论】:

以上是关于asp.net core mvc cors请求被拒绝[重复]的主要内容,如果未能解决你的问题,请参考以下文章

jQuery+ASP.NET MVC基于CORS实现带cookie的跨域ajax请求

处理对 ASP.NET MVC 操作的 CORS 预检请求

ASP.NET 5 MVC 6 CORS vue.js 请求不允许

即使在配置 ASP.NET Core Web API 中启用了 CORS,CORS 也会阻止发布请求

放置请求期间的 ASP Net Core CORS 错误

在 ASP.Net 5 / Core 中启用跨域资源共享 (CORS)