【发布时间】:2019-02-02 01:24:27
【问题描述】:
从我的 Angular 应用程序调用 POST 或 DELETE Core API 时出现 CORS 错误。
我的核心 Web API 配置了 Windows 身份验证。 [Authorize] 属性在控制器级别。 每当我从 Angular 传递一个 GET 请求时,该请求就会获得授权,并且我会收到响应。
当从 Angular 向 Core API 发送 POST 请求时,
1) 如果我将数据作为 FormData 从 Angular 服务传递到 Core API,它工作正常。
2) 如果我将数据作为模型从 Angular 服务传递到核心 API,我会收到以下错误
无法加载http://localhost:63854/api/sampleController/1:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 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 传递数据时不会发生) - DELETE 和 POST 请求都给出相同的异常。
HTTP 错误 401.2 - 未经授权 - 由于身份验证标头无效,您无权查看此页面
我喜欢将模型从 Angular 传递给 Core API 而不是 FormData。
【问题讨论】:
-
我很久以前刚开始的时候也有类似的事情。不记得了,但也许可以尝试将 app.UseCors("AllowAll");` 放在 Configure 方法的底部。我认为这与订购有关。
标签: c# angular asp.net-core cors