【发布时间】:2019-05-14 09:01:43
【问题描述】:
我尝试在 dotnet webapi 项目和 angular6 项目之间进行通信。
场景:当我输入登录名和密码并单击登录按钮时,它应该从服务器获取 access_token、用户名并将结果显示在 displayresult.html 中。 我知道以前有人问过这个问题,但即使在尝试了所有这些之后 解决方案,我无法与 dotnetwebapi 交流我的 angular6 项目。
为了修复 CORS 政策,我在我的 dotnetwebapi 项目中进行了一些更改。
在
ConfigureAuth(IAppBuilder app)的startup.auth.cs中添加了app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);。在
web.config中,添加了自定义headers,请看下面的代码。
authservice.ts
export class AuthService
{
private TokenAPI="http://localhost:51255/token";
login(username:string,password:string):Observable<TokenParams>
{
var headersfortokenapi = new Headers({'Content-Type':'application/x-www-form-encoded'});
var data="grant_type=password&username=" + username + "&password=" + password;
return this.objhttp.post(this.TokenAPI,data,{ headers:headersfortokenapi})
.pipe(
map(res=>res.json()
)
);
}
}
Login.component.ts
OnLoginClick()
{
this.objauthservice.login(this.username,this.password)
.subscribe
(
data=>
{
this.tokenparam=data;
this.objauthservice.AccessToken=this.tokenparam.access_token;
this.objroute.navigate(['/Displayproducts']);
}
)
}
当我点击登录页面中的登录按钮时,它会转到上述方法并调用 authservice 登录方法。
现在我创建了TOKENWEBAPIPROJECT dotnet 项目。
该项目在http://localhost:51255/token 中运行。
我在TOKENWEBAPIPROJECT中做了一些更改的代码sn-p。
startup.cs
public void ConfigureAuth(IAppBuilder app)
{
//it has the default code for connecting to dbcontext and application
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS,token"/>
<add name="Access-Control-Allow-Headers" value="Origin, application/x-www-form-encoded, Content-Type, X-Auth-Token" />
</customHeaders>
</httpProtocol>
</system.webServer>
我在 Postman 中测试了http://localhost:51255/token 的 post 请求。
在这里我发送用户名、密码、grant_type=password 并返回正确的 access_token、用户名、token_type 等。
预期:当我输入登录名和密码并单击登录按钮时,它应该从服务器获取 access_token、用户名并在displayresult.html 中显示结果。
实际:相反,我收到以下错误:-
1.OPTIONS http://localhost:51255/token 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:51255/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
【问题讨论】:
-
您可以尝试将您的
值更新为“*”吗? -
是的,我试过了,然后也会发生同样的错误。
-
我认为您还必须在 webapi 后端允许标头
X-Requested-With。
标签: cors rxjs angular6 asp.net-web-api2 owin