仍然收到错误消息,已被CORS政策阻止

用户名

我在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)
萨耶塔兰(Sajeetharan)

我想你需要 AllowAnyOrigin

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

或通过原点

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么我会收到 Cors 错误:...已被 CORS 政策阻止

文件上传已被CORS政策阻止

Stackexchange REST API 已被 CORS 政策阻止

WordPress 发布失败;javascript 显示错误“访问获取...已被 CORS 政策阻止”

Django Vue Js Axios 已被 CORS 政策阻止

“...已被 CORS 政策阻止:没有‘访问控制允许来源’”

从源“S3_host_url”获取“API_Gateway_URL”的访问已被 CORS 政策阻止

已被CORS政策阻止:对预检请求的响应未通过访问控制检查

尝试使用axios访问Wikipedia Api,但收到CORS政策错误

flask_cors 已注册但仍然收到 CORS 错误

使用 require('cors') 但仍然收到 CORS 错误

启用了Typescript CORS,但仍然收到CORS错误

Blazor请求被CORS政策阻止

Axios请求:被CORS政策阻止

Angular Front - Cloud Functions 上的 NEST JS - 已被 CORS 政策阻止:没有“访问控制允许来源”

URL 已被 CORS 策略阻止

我在Rails应用中设置了CORS,但仍然收到错误

javascript:由于通配符而被CORS政策阻止

向被 CORS 政策阻止的 API 发布请求

Google Play商店无法上传带有“被CORS政策阻止”错误的应用程序图标

CORS政策已被我的子域屏蔽

Google OAuth2:重定向已被CORS政策阻止:请求需要进行预检,不允许遵循跨域重定向

对XMLHttpRequest的访问已被CORS策略阻止

如何修复XMLHttpRequest已被CORS策略阻止

Post API 的问题:“已被 CORS 策略阻止......”

Vue。js CORS问题,后端数据被CORS政策阻止

仅针对 Angular 7 Web 应用程序中的“https://localhost:44361/connect/token”出现“被 CORS 政策阻止”的错误

Vue devServer代理没有帮助,我仍然收到CORS错误

在服务器上启用的CORS仍然收到标头错误