【问题标题】:still get error on has been blocked by CORS policy [closed]仍然出现错误已被 CORS 政策阻止 [关闭]
【发布时间】:2020-01-02 04:38:48
【问题描述】:

我有一个带有 Angular 8 的 asp.net core 3 应用程序。所以在 Angular 中我有这个方法:

 getValues() {
    this.http.get('https://localhost:44323/api/Values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    });
  }

我的 cs 文件看起来像这样:

 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)
        {

            string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(connectionString));

            services.AddCors();

            services.AddControllers();
        }

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors();

            app.UseAuthorization();

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

            app.UseCors(x => x.WithOrigins().AllowAnyMethod().AllowAnyHeader());

        }
    }

所以我正在做 UseCors 的事情。但我仍然收到此错误:

Access to XMLHttpRequest at 'https://localhost:44323/api/Values/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当然,我用谷歌搜索了这个错误。这就是我使用 UseCors 的原因。但这是他们推荐的。但我仍然得到这个错误。

所以我被困住了。如果有人能告诉我我做错了什么会很好。

谢谢

我现在是这样的:

[EnableCors("AllowOrigin")]
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        private protected DataContext _dataContext;
        public ValuesController( DataContext dataContext)
        {
            this._dataContext = dataContext;
        }
        // GET api/values
        [HttpGet]
        [EnableCors("AllowOrigin")]
        public async Task <IActionResult> GetValues()
        {
            var values = await _dataContext.Values.ToListAsync();

            return Ok(values);

        }

        // GET api/values/5
        [HttpGet("{id}")]
        public async Task <IActionResult> GetValue(int id)
        {
            var value = await _dataContext.Values.FirstOrDefaultAsync(x => x.Id == id);

            return Ok(value);
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

还有这个:


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)
        {

            string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
            options.UseSqlServer(connectionString));

            services.AddCors();
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddControllers();
        }

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

            app.UseHttpsRedirection();

            app.UseRouting();

            //app.UseCors();

            app.UseAuthorization();

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

            app.UseCors(x => x.WithOrigins("https://localhost:44323").AllowAnyHeader().AllowAnyMethod().AllowCredentials());

        }
    }

但是我会得到这个错误:

An unhandled exception occurred while processing the request.
InvalidOperationException: Endpoint DatingApp.API.Controllers.ValuesController.GetValues (DatingApp.API) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code.
Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)

【问题讨论】:

  • 嘿,您是否尝试过使用代理重定向? angular.io/guide/build#proxying-to-a-backend-server
  • 我没试过。但是,好吧,这必须有效。我不明白为什么它不起作用
  • 很好的请求总是很难处理
  • 告诉我它是否有效;)

标签: javascript c# angular .net-core


【解决方案1】:

好的,我终于解决了!!

我不知道。诀窍是我是这样做的:


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

            app.UseHttpsRedirection();

            app.UseRouting();

            //app.UseCors();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseAuthorization();

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

So between routing and Authorization. 

以及以不好的方式对我的帖子投票的人。以你为耻!!

【讨论】:

    【解决方案2】:

    我猜你需要 AllowAnyOrigin

    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    

    或通过原点

     app.UseCors(x => x.WithOrigins('https://localhost:44323').AllowAnyMethod().AllowAnyHeader());
    

    【讨论】:

    • 谢谢。是的,我试过了。但是还是报错
    • 你需要添加 .AllowCredentials();
    • 并删除重复的 UseCors
    • 好的,你需要添加 .AllowCredentials();没试过。但是我必须在哪里添加这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2020-06-29
    • 2019-12-19
    • 2018-03-22
    • 2020-07-29
    • 2021-09-17
    • 2017-07-05
    相关资源
    最近更新 更多