angular - 对源地址 'http://localhost:4200' 处的 XMLHttpRequest 的访问已被 CORS 策略阻止

标签 angular .net-core cors

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

访问位于“https://localhost:44378/api/test”的 XMLHttpRequest '来自原点'http://localhost:4200 ' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin” header 。

我按照 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://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

我尝试了下面给出的代码,但收到此错误:

enter image description here

这是更改后的代码:

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

下面是我的 Controller :

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

        }

任何帮助将不胜感激。

最佳答案

正如您在 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");

关于angular - 对源地址 'http://localhost:4200' 处的 XMLHttpRequest 的访问已被 CORS 策略阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60910314/

相关文章:

javascript - 从指令在主机上触发事件

c# - ASP.NET 核心 2.2 : Unable to resolve service for type 'AutoMapper.IMapper'

jquery - SSL CORS 不适用于 Zend Guard

spring - Spring Boot 的 CORS 问题

javascript - 在 Angular2 中加载具有 document.write 的外部 JS

Angular 2 模板使用 console.log

linux - 如何让我的 dotnet 核心应用程序使用不同的包?

c# - 初始化数组时出现 StackOverflow 异常

rest - Haskell Yesod - 执行 POST 请求时浏览器 OPTIONS 请求的 CORS 问题

angular - 拒绝加载图像,因为它违反了以下内容安全策略指令(favicon)