[英]Angular 6 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
I'm getting CORS error when calling a POST or DELETE Core API from my Angular application. 从我的Angular应用程序调用POST或DELETE Core API时出现CORS错误。
My Core Web API's are configured with Windows Authentication. 我的Core Web API配置了Windows身份验证。 And [Authorize] attribute is at controller level.
并且[Authorize]属性处于控制器级别。 Whenever I pass a GET request from Angular, the request is getting authorized and I'm getting the response back.
每当我从Angular传递GET请求时,请求都会获得授权,我会收到响应。
When sending a POST request from Angular to Core API, 从Angular向Core API发送POST请求时,
1) If I pass data as FormData from Angular service to Core API, it is working fine. 1)如果我将FormData中的数据从Angular服务传递到Core API,它工作正常。
2) If I pass data as Model from Angular service to Core API, I'm getting the below error 2)如果我将数据作为模型从Angular服务传递到Core API,我收到以下错误
Failed to load http://localhost:63854/api/sampleController/1 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
无法加载http:// localhost:63854 / api / sampleController / 1 :对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:52871 ' is therefore not allowed access
因此不允许来源' http:// localhost:52871 '访问
Here is Startup.cs 这是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();
}
Core API action method: 核心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 Service: accessType is constructed in component, and passed as object to angular service. 角度服务: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);
}
Complete error message (But this is happening only when passing data as modal, not happening when passing data as FormData) - Both DELETE and POST requests gives the same exception. 完整的错误消息(但这只在将数据作为模态传递时发生,而不是在将数据作为FormData传递时发生) - DELETE和POST请求都给出了相同的异常。
HTTP Error 401.2 - Unauthorized - You are not authorized to view this page due to invalid authentication headers
HTTP错误401.2 - 未经授权 - 由于身份验证标头无效,您无权查看此页面
I like to pass model from Angular to Core API instead of FormData. 我喜欢将模型从Angular传递给Core API而不是FormData。
Try using below in Configure
method instead: 请尝试在
Configure
方法中使用以下内容:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
}
If you want to use Cors, in combination with Windows Authentication, you have to enable also the "Anonymous Authentication". 如果要使用Cors,结合Windows身份验证,还必须启用“匿名身份验证”。 Tried all other solutions, but with no success.
尝试了所有其他解决方案,但没有成功。
In Angular, I had to implement HttpInterceptor to put it to work. 在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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.