首页 > 解决方案 > Angular 6 对 .NET Core API 的基本身份验证发布请求

问题描述

这个问题已经发布了很多次,但我尝试了几个解决方案,但它们对我不起作用。我正在制作一个 API 服务,需要使用基本身份验证来获取承载令牌以用于其他端点。API 是用 .NET Core 编写的。

我的代码很简单:

private GetToken() {
    let delta = new Date().getTime() - this.tokenTimestamp.getTime();

    const options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json', 
            'Cache-Control': 'no-cache',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, content-type',
            'Authorization': 'Basic ' + btoa(this.user + ':' + this.pass)
        })
    };

    console.log(options);

    if (delta >= 60000) {
        this.http.post<Response>(this.url + '/api/Auth/Token/', { username: this.user, password: this.pass }, options)
        .subscribe(
        (val) => {
            console.log("POST call successful value returned in body", val);
        },
        response => {
            console.log("POST call in error", response);
        },
        () => {
            console.log("The POST observable is now completed.");
        });
    }
}

我在控制台中收到 CORS 错误(我认为): 在此处输入图像描述

非常感谢您的帮助!

标签: angularapipost.net-coreangular6

解决方案


即使看起来存在 CORS 问题,可能真的存在也可能不存在,但首先您需要解决 404 Not Found 错误。同样在我们的应用程序中,当出现 404 Not Found 时,即使 CORS 配置已完美设置,404 错误通常也会伴随着 CORS 错误。

要对此进行测试,请打开 Postman。向您的 localhost:50897/api/Auth/Token/ 创建一个 POST 请求,看看您是否仍然收到 404。如果是,您将考虑确保您的端点是好的。

编辑:

在你的 Startup.cs 中,确保你在 Configure(..) { } 中有这个

app.UseCors(builder => builder
                        .WithOrigins("http://localhost:4200", "url2") // url2 would be the IP address that your angular app is deployed under in IIS
                        .AllowCredentials()
                        .AllowAnyHeader()
                        .AllowAnyMethod());

推荐阅读