无法从 API(dotNet Core)获取数据(使用角度)没有“Access-Control-Allow-Origin”
Posted
技术标签:
【中文标题】无法从 API(dotNet Core)获取数据(使用角度)没有“Access-Control-Allow-Origin”【英文标题】:Cant get data (using angular) from the API (dotNet Core) No '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();
);
【问题讨论】:
试试这个链接 (andrewlock.net/a-deep-dive-in-to-the-asp-net-core-cors-library) 它可能会帮助你正确配置。AllowAnyHeader
不能与AllowCredentials
一起使用。如果要允许凭据,则需要明确列出允许的标头。
尝试引用this。
【参考方案1】:
在 ConfigureServices 中试试这个:
services.AddCors(
options =>
options.AddPolicy(
"Any",
cors =>
cors.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
);
);
然后在配置中:
app.UseCors("Any")
【讨论】:
以上是关于无法从 API(dotNet Core)获取数据(使用角度)没有“Access-Control-Allow-Origin”的主要内容,如果未能解决你的问题,请参考以下文章
在 dotnet core web api ::ffff:127.0.0.1 中获取客户端 IP 地址
dotnet core docker web api没有连接
Dotnet Core API - 获取控制器方法的 URL
dotnet core webapi json-api 兼容查询字符串路由