【问题标题】:Access to XMLHttpRequest at origin 'http://localhost:4200' has been blocked by CORS policyCORS 策略已阻止访问源“http://localhost:4200”的 XMLHttpRequest
【发布时间】:2020-07-09 15:03:29
【问题描述】:

我正在尝试从我的 Angular 应用程序调用我的 .net Core API,但我收到一条错误消息

从源“http://localhost:4200”访问“https://localhost:44378/api/test”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我按照 Microsoft 文章的说明对我的 startup.cs 文件进行了所有更改,但仍然出现上述错误。下面是我的 Startup.cs 文件:

  public void ConfigureServices(IServiceCollection services)
            {



                    services.AddCors(options =>
                    {
                        options.AddPolicy(MyAllowSpecificOrigins,
                        builder =>
                        {
                            builder.WithOrigins("http://localhost:4200")
                                                 .AllowAnyHeader()
                                                .AllowAnyOrigin()
                                                .AllowAnyMethod();

                        });
                    });


                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                    services.AddControllers();
                   services.AddDbContext<db_recloadContext>();

            }

在我的配置方法中,我有以下代码:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
            //app.UseCors(MyAllowSpecificOrigins);
            app.UseCors(builder => builder
            .WithOrigins("http://localhost:4200") /* list of environments that will access this api */
            .WithMethods("GET", "OPTIONS") /* assuming your endpoint only supports GET */
            .WithHeaders("Origin", "Authorization") /* headers apart of safe-list ones that you use */
            );


            app.UseHttpsRedirection();
            //app.UseMvc();
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

我按照以下 Microsoft 文章将 CORS 放入我的 startup.cs 文件中。

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

我尝试了下面给出的代码,我得到了这个错误:

这是修改后的代码:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200" }).AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.AddControllers();
               services.AddDbContext<db_recloadContext>();

        }

在配置方法中,我有以下代码:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
            app.UseRouting();
            app.UseCors("CorsPolicy");
           app.UseHttpsRedirection();

           app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

下面是我的整个 startup.cs 文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SpaServices;
using RecLoad.Models.DB;
namespace RecLoad
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            //services.AddCors(options =>
            //{
            //    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            //});
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy",
            //    builder =>
            //    {
            //        builder.WithOrigins("http://localhost:4200")
            //                             .AllowAnyHeader()
            //                            .AllowAnyOrigin()
            //                            .AllowAnyMethod();

            //    });
            //});

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200", "https://localhost:44378/api/recloadprime" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin:http://localhost:4200");
                });
            });
            //response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
            //response.Headers.Add("Access-Control-Allow-Origin", "*");
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.WithHeaders("Access-Control-Allow-Origin:http://localhost:4200", "Access-Control-Expose-Headers").AllowAnyMethod().AllowAnyOrigin());
            //});



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.AddControllers();
               services.AddDbContext<db_recloadContext>();
        }

        // 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();

            }
            else
            {
                app.UseHsts();
            }

            app.UseCors("CorsPolicy");
           app.UseHttpsRedirection();
            app.UseRouting();

            app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

下面是我的控制器:

namespace RecLoad.Controllers
{
    [Route("api/[controller]")]
    //[EnableCors("AllowAnyCorsPolicy")]
    public class RecLoadPrimeController : ControllerBase
    {
        private readonly db_recloadContext _context;

        public RecLoadPrimeController(db_recloadContext context)
        {

            _context = context;
        }

        [HttpGet]
        public ActionResult<string> Get()
        {

            return "This is a test";

        }

任何帮助将不胜感激。

【问题讨论】:

    标签: angular .net-core cors


    【解决方案1】:

    正如您在Microsoft's documentation 看到的那样。 首先添加 Cors 服务

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200", "http://yourdomain.com" }).AllowAnyMethod().AllowAnyHeader();
                });
            });
    

    然后在Configure方法中使用

    app.UseCors("CorsPolicy");
    

    【讨论】:

    • 请看我上面的帖子:我在 configureservices 方法中添加了 CORS 服务,然后在 configure 方法中使用了 CORS 策略。我只是在 startup.cs 文件中使用了两种不同的方法
    • 我已经仔细阅读了您的问题,请尝试一下。我遇到了你的问题,这段代码正在运行。
    • 我试过你的代码。请参阅上面的错误。我还发布了我收到的错误以及您给我的代码。
    • 如果您需要任何其他信息,请告诉我。我真的很沮丧,过去 2 天我一直在尝试这个。
    • 按域名,我应该把我的 api URL 像这样:localhost:44378/api/recloadprime
    【解决方案2】:

    删除或注释掉Configure 方法中的app.UseHttpsRedirection(); 以使错误消失。

    【讨论】:

    • 我删除了 app.UseHttpsRedirection();。错误并没有消失
    猜你喜欢
    • 2020-01-26
    • 2019-10-31
    • 2020-10-12
    • 1970-01-01
    • 2019-11-17
    • 2019-07-25
    • 1970-01-01
    • 2023-02-07
    • 2021-12-26
    相关资源
    最近更新 更多