我已经阅读了所有的解决方案,到目前为止我都试过了,没有一个有效.

我有一个ASP.NET Core8Web API后端和一个混合的.NET8/ANGLE 15前端.前端应用程序可以向API发出GET个请求,但有POST个请求被CORS阻止.

我已经在接口中try 了以下几种方式:

builder.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder => {
                builder.WithOrigins("http://localhost:1859");
                builder.WithMethods("GET", "POST");
                builder.AllowAnyHeader();
            });
        });

app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();

与.一起

builder.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder => {
                builder.AllowAnyOrigin();
                builder.AllowAnyMethod();
                builder.AllowAnyHeader();
            });
        });

The controller method (I've tried with 和 without [EnableCors()]):

[HttpPost] 
public async Task<int> Save(SaveContractRequest req)

Angular 服务方法:

saveContract(req: SaveContractRequest) {
    return this.http.post<number>(this.settingsSvc.apiEndpoint + ReimbursementEndPoints.CONTRACTS_SAVE, req);
}

然而,我总是得到这样的错误:

CORS策略已阻止在‘http://localhost/evms.api/api/Reimbursement/Contracts/Save’从源http://localhost:1859‘访问XMLHttpRequest.请求的资源上不存在"Access-Control-Allow-Origin"标头.

I'm at a loss. I can't get any more permissive than "allow any origin, any header, 和 any method". Why doesn't this work? Why can't I call a controller with a POST method?

推荐答案

您应该在启用跨域资源共享(CORS)之前使用app.UseStaticFiles(); app.UseRouting(),以便识别您的路径

middleware pipeline

执行的顺序将是

var app = builder.Build();

app.UseHttpsRedirection();

app.UseStaticFiles(); // 🔴 here it is
app.UseRouting(); // 🔴 here it is

app.UseCors();
app.UseAuthorization();

链接:UseCors and UseStaticFiles order

Angular相关问答推荐

从嵌套组件导航到命名路由中的顶级路由

Angular中的Bootstrap carousel动态属性

以17角表示的自定义元素

ANGLING HTTP.GET()返回包含数据的数组

Angular react 形式验证问题

ANGLING:ExpressionChangedAfterChecked在嵌套形式中由子项添加验证器

Angular 15 在 URL 中使用@进行路由

如何在 Angular 库中将依赖项声明为可选?

包含与 ngFor 相关内容的 HTML 输入

如何以Angular 改变环境

RxJS 基于先前的数据响应执行请求(涉及循环对象数组)

如何从组件模板将数组作为 Input() 传递?

Electron - 不允许加载本地资源

Angular 2从assets文件夹加载CSS背景图像

Angular:找不到不同的支持对象[object Object]

NG2-Charts 无法绑定到 datasets,因为它不是 canvas的已知属性

Angular Material2 主题 - 如何设置应用程序背景?

在 Angular 组件模板中添加脚本标签

Angular 4 错误:没有 HttpClient 的provider提供者

'Observable' 类型上不存在属性 'filter'