【问题标题】:asp.net core mvc cors request denied [duplicate]asp.net core mvc cors请求被拒绝[重复]
【发布时间】:2023-03-27 20:56:02
【问题描述】:

我一直在开发一个新的 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?}");
        });
    }
}

【问题讨论】:

    标签: asp.net-mvc cors asp.net-core-mvc


    【解决方案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?}");
            });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-14
      • 2021-03-27
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2019-01-18
      • 2021-08-26
      相关资源
      最近更新 更多