gpt4 book ai didi

c# - Angular 6 - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header

转载 作者:太空狗 更新时间:2023-10-29 18:36:54 24 4
gpt4 key购买 nike

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

我的核心 Web API 配置了 Windows 身份验证。 [Authorize] 属性处于 Controller 级别。每当我从 Angular 传递 GET 请求时,该请求都会获得授权并且我会收到响应。

当从 Angular 向 Core API 发送 POST 请求时,

1) 如果我将数据作为 FormData 从 Angular 服务传递到核心 API,它工作正常。

2) 如果我将数据作为模型从 Angular 服务传递到核心 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. Origin 'http://localhost:52871' is therefore not allowed access

这是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 Service: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 Error 401.2 - Unauthorized - You are not authorized to view this page due to invalid authentication headers

我喜欢将模型从 Angular 传递到 Core API 而不是 FormData。

最佳答案

尝试在 Configure 方法中使用下面的方法:

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

关于c# - Angular 6 - 对预检请求的响应未通过访问控制检查 : No 'Access-Control-Allow-Origin' header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52040443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com