我有一个本地运行的ASP.NET核心API服务和一个本地Angular App。我的大多数调用都可以使用该API,但是一次调用却不断给我带来CORS错误。我怀疑是因为这是后期操作?根据CORS,帖子需要其他内容吗?
丑角ts:
loadGroup(groupName:string){
this.apiService.getInfluencersWithFilter(this.query,groupName,null,null,this.ageRanges).subscribe((data) => {
this.influencerSearchResult = data.results;
// this.searchGroupsFacet = data.facetGroupList;
this.searchSubGroupsFacet = data.facetSubGroupList;
this.showSubGroups = true;
});
}
角度服务:
getInfluencersWithFilter(q:string, group:string, subGroups:string[], socialAccounts:string[],ageRanges:AgeRange[]):Observable<InfluencerSearchContainer>
{
if(q==null)
{
q = "";
}
var url = `${environment.apiDomain}/api/InfluencersSearch/`;
return this.httpClient.post<InfluencerSearchContainer>(url,{q:"",group:group,subGroups:subGroups, socialAccounts:socialAccounts, ageRanges:ageRanges}).pipe(
map(x => new InfluencerSearchContainer(x)));
}
启动ASP.NET核心:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<DocumentClient>((s) =>
{
string EndpointUrl = Configuration["CosmosDB:EndpointUrl"];
string PrimaryKey = Configuration["CosmosDB:PrimaryKey"];
return new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
});
var connStr = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<DB>(options => options.UseSqlServer(connStr));
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowSpecificOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}
和控制器:
[HttpPost]
public InfluencerSearchResultWithFacets Post([FromBody] InfluencerQuery q)
{
return GetSearchResult(q.q, q.group,q.subGroups, q.socialAccounts, q.ageRanges);
}
我有什么想念的吗?我认为这里一切都被禁用了吗?在我撰写本文时,我怀疑它与Post有关,因为get操作有效。
我还在控制器上添加了以下内容: [EnableCors(“ AllowSpecificOrigin”)]
答案 0 :(得分:1)
有时候
1)如果api中的请求有效负载(或)错误,则chrome开发人员工具控制台会显示CORS。
请console.log请求并使用postman / swagger分别测试api。
如果1)无法解决问题
2)有时IIS在默认情况下可以阻止PUT和POST操作。请参阅this。
如果1)和2)无法解决问题
这也可能是一个问题
3)我们可能必须向控制器添加[EnableCors(“ AllowSpecificOrigin”)]。