首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CORS策略已阻止对源http://localhost:4200‘处XMLHttpRequest的访问

CORS策略已阻止对源http://localhost:4200‘处XMLHttpRequest的访问
EN

Stack Overflow用户
提问于 2020-03-29 12:54:42
回答 2查看 1.2K关注 0票数 0

我正在尝试从我的angular应用程序调用我的.net核心应用程序接口,但我得到一个错误消息:

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

我按照微软文章中的说明对我的startup.cs文件进行了所有更改,但仍然收到上面的错误。下面是我的Startup.cs文件:

代码语言:javascript
复制
  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>();

            }

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

代码语言:javascript
复制
 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();
            });
        }

为了将CORS放入我的startup.cs文件中,我遵循了下面的微软文章。

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

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

以下是更改后的代码:

代码语言:javascript
复制
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>();

        }

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

代码语言:javascript
复制
 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文件:

代码语言:javascript
复制
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();
            });
        }
    }
}

下面是我的控制器:

代码语言:javascript
复制
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";

        }

任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-29 13:07:50

正如你在Microsoft's documentation看到的。第一次添加Cors服务

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

然后在Configure方法中使用它

代码语言:javascript
复制
app.UseCors("CorsPolicy");
票数 2
EN

Stack Overflow用户

发布于 2020-03-31 14:12:25

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60910314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档