angular - 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 问题,可能真的存在也可能不存在,但首先您需要解决 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());
推荐阅读
- swift - 在 Swift 函数设计中什么时候应该有参数标签,什么时候应该省略参数标签?
- linux - 如何将动作直接发送到输入事件?
- python - 如何从多维列表的第二个列表中找到 numpy.amax?
- arrays - 为什么在尝试分配一个变体时,某个非 IDispatch 公开对象类型的数组,而是分配了数组指针?
- ios - SpriteKit 类别BitMask 问题
- reactjs - 在示例中显示 createRef 意外令牌错误的反应传单
- xamarin - 在 Azure Pipelines 上构建时,是否有可用版本的 MSBuild 列表可供选择?
- c - 如何在c中生成0到1之间的对称序列(每个部分的元素数量相同)?
- python - 根据 PEP8 标准和 python 换行技术分解字符串格式的代码行的最佳方法是什么?
- node.js - 如何在猫鼬中填充引用另一个模式的对象数组