从我的Angular应用程序调用POST或DELETE Core API时出现CORS错误 .
我的Core Web API配置了Windows身份验证 . 并且 [Authorize] 属性处于控制器级别 . 每当我从Angular传递GET请求时,请求都会获得授权,我会收到响应 .
从Angular向Core API发送POST请求时,
1)如果我将FormData中的数据从Angular服务传递到Core API,它工作正常 .
2)如果我将数据作为模型从Angular服务传递到Core API,我收到以下错误
无法加载http:// localhost:63854 / api / sampleController / 1:对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:52871'访问
这是Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAll");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIs"));
app.UseMvcWithDefaultRoute();
}
核心API操作方法:
[Authorize]
[Produces("application/json")]
[Route("api/someRoute")]
public class someController : Controller
{
[HttpPost]
[Route("update")]
public async Task<HttpResponseMessage> UpdateAccessType([FromBody] TestModel modalObj)
{
//code..
}
[HttpDelete("{id}")]
public async Task<HttpResponseMessage> DeleteAccessType(string id)
{
//code..
}
}
角度服务:accessType在组件中构造,并作为对象传递给角度服务 .
updateAccessType(accessType) {
return this.http.post(this.apiUrl + "api/someController/update", accessType);
}
deleteAccessType(accessLookupId: string) {
return this.http.delete(this.apiUrl + "api/someController/" + accessLookupId);
}
完整的错误消息(但这只在将数据作为模态传递时发生,而不是在将数据作为FormData传递时发生) - DELETE和POST请求都给出了相同的异常 .
HTTP错误401.2 - 未经授权 - 由于身份验证标头无效,您无权查看此页面
我喜欢将模型从Angular传递给Core API而不是FormData .
2 回答
请尝试在
Configure
方法中使用以下内容:如果要使用Cors,结合Windows身份验证,还必须启用“匿名身份验证” . 尝试了所有其他解决方案,但没有成功 .
在Angular中,我必须实现HttpInterceptor才能使它工作 .