【发布时间】:2019-09-26 10:27:23
【问题描述】:
我正在运行 ASP.NET Core Angular 应用程序,我在 Core 应用程序中添加了一个 Api 控制器,我试图从 Angular 应用程序进行 api 调用,Core 应用程序托管在 58181 上,Angular 应用程序托管在 44337 上,当我尝试从 Angular 调用 Api
Access to XMLHttpRequest at 'http://localhost:58181/api/authenticate/login' from origin 'https://localhost:44337' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
我在 API 中配置 Cors
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("CorsPolicy");
我正在尝试像这样调用 API
register() {
var body = {
UserName: this.formModel.value.UserName,
Email: this.formModel.value.Email,
FullName: this.formModel.value.FullName,
Password: this.formModel.value.Passwords.Password
};
return this.http.post(this.BaseURI + '/authenticate/register', body, {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json',
'Authorization':'authkey',
'userid':'1'
})});
}
我期望调用我的身份验证控制器并登录/注册我的用户,Angular 应用程序和 API 都将位于同一个本地主机上,在不同的端口上。
【问题讨论】:
-
您实际上不需要设置
Content-Type标头,因为您正在使用HttpClient。此外,Access-Control-Allow-Origin是针对跨域请求的 Options 调用的响应标头。所以你也不需要在你的请求头中设置它。 -
Angular 应用程序在浏览器中运行,它们没有端口。我有点困惑你如何有两个不同的端口。您是否使用
angular-cli并使用ng-serve和proxy-conf代理您的请求?你有两个核心应用吗?
标签: angular api http asp.net-web-api cors