【发布时间】: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();
});
}
}
}
【问题讨论】:
-
试试这个链接 (andrewlock.net/a-deep-dive-in-to-the-asp-net-core-cors-library) 它可能会帮助你正确配置。
-
AllowAnyHeader不能与AllowCredentials一起使用。如果要允许凭据,则需要明确列出允许的标头。 -
尝试引用this。
标签: c# angular asp.net-core cors