我在localhost:5000上运行了一个dot net core API。 我添加了
services.AddCors();
到ConfigureServices方法,
app.UseCors(builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
到StartUp中的Configure方法。
我有一个正在尝试的js客户端
return fetch('http://localhost:5000/api/Authorization', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
UserName: userName,
Password: password,
})}).then((response) => response.json())
.then((responseJson) => {return responseJson.userIsAdmin});
}
但是当最后一次执行时,浏览器拒绝,说:
请求时没有'Access-Control-Allow-Origin'标头 资源。因此不允许来源“http://localhost:3000” 访问。响应的HTTP状态代码为500。
研究指出已在上述API项目中实施的解决方案。我错过了什么?
答案 0 :(得分:0)
您限制为特定来源:builder.WithOrigins("http://localhost:3000")
,这意味着您的应用的请求来源只能是http://localhost:3000,然后允许任何来源。
从最少量的CORS限制开始,然后从那里开始工作:
app.UseCors(builder => builder
.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
有关详细信息,请参阅this guide。
答案 1 :(得分:0)
您是否也将标志添加到控制器?将EnableCors
标志添加到授权控制器。
[EnableCors]
public class AuthorizationController
答案 2 :(得分:0)
所以我的解决方案是其中一个评论和一个答案的组合。解决问题"
1 - 修复导致“响应有HTTP状态码500 ”的系统错误,如sideshowbarker所述(谢谢)。就我而言,我暂时在webapi中启用静态文件,并将我的网页放在wwwroot中。这是我完全避免使用CORS此外,如果我只关注DEBUG CONSOLE并注意到正在流动的堆栈轨道,我会很快发现500错误。
2 - 修复500错误原因并关闭静态文件后,我不得不更改我的app.UseCors代码部分以匹配Brian Ogden(谢谢)答案:
app.UseCors(builder => builder
.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());