【问题标题】:Cant get data (using angular) from the API (dotNet Core) No 'Access-Control-Allow-Origin'无法从 API(dotNet Core)获取数据(使用角度)没有“Access-Control-Allow-Origin”
【发布时间】:2021-11-29 02:32:12
【问题描述】:

从源“http://localhost:4200”访问“https://localhost:5001/api/users”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。 我也试过 AllowAnyOrigin();同样的错误, 和 .SetIsOriginAllowed(origin => true));同样的错误。

Angular (app.component.ts)

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Testing SPA';
  users :any;

  constructor (private http: HttpClient) {}
  ngOnInit(){
    this.getUsers();
  }

  getUsers (){
    this.http.get('https://localhost:5001/api/users').subscribe(response => {this.users = response;},error =>{console.log(error);})
  }

}

dotNet (startup.cs)

namespace API
{
    public class Startup
    {
        private readonly IConfiguration _config;
        public Startup(IConfiguration config)
        {
            _config = config;           
        }



        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlite(_config.GetConnectionString("DefaultConnection"));
            });
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
            });
            
        }

        // 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.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
            }
            
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(x => x.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
                .WithOrigins("http://localhost:4200"));
            app.UseAuthorization();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

【问题讨论】:

标签: c# angular asp.net-core cors


【解决方案1】:

在 ConfigureServices 中试试这个:

  services.AddCors(
    options =>
    {
      options.AddPolicy(
        "Any",
        cors =>
        {
            cors.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
        });
    });

然后在配置中:

app.UseCors("Any")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2023-01-12
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2018-09-06
    • 2017-04-15
    相关资源
    最近更新 更多