Angular 6-对预检请求的响应未通过访问控制检查:无“ Access-Control-Allow-Origin”标头

时间:2018-08-27 13:24:08

标签: c# angular asp.net-core cors

从Angular应用程序调用POST或DELETE Core API时出现CORS错误。

我的核心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..
    }
}

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。

2 个答案:

答案 0 :(得分:1)

请尝试使用下面的Configure方法代替

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
}

答案 1 :(得分:0)

如果要与Windows身份验证结合使用Cors,则还必须启用“匿名身份验证”。 尝试了所有其他解决方案,但没有成功。

在Angular中,我必须实现HttpInterceptor才能使其正常工作。

import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
    });

    return next.handle(request);
  }