当从我的Angular应用程序调用Core API的POST或DELETE时,我会收到CORS错误。
我的Core Web API配置了Windows身份验证。在控制器级别上有[Authorize]
属性。
每当我从Angular传递GET请求时,请求被授权并且我收到了响应。
当我从Angular发送POST请求到Core API时,
1)如果我从Angular服务将数据传递为FormData到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..
}
}
Angular服务:accessType在组件中构建,作为对象传递给Angular服务。
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时不会出现此问题)-删除和发布请求都会产生相同的异常。
HTTP错误401.2-未经授权-由于无效的身份验证标头,您无权查看此页面
我想将模型从Angular传递到Core API,而不是使用FormData。
app.UseCors("AllowAll");
放在 Configure 方法的最后面。我想这可能与顺序有关。 - James