更新时间:2021-10-20 05:23:31
我找到了解决方案.感谢 API 站点上的评论:http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
I found the solution. Thanks to the comments on the API site: http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
我必须为 application/x-www-form-urlencoded 设置正确的标题;charset=UTF-8 并序列化我发布的对象.我找不到 Angular 序列化器方法,所以我在 JavaScript 中制作了自己的(从另一个 *** 站点复制).
I had to set the correct header for application/x-www-form-urlencoded; charset=UTF-8 and serialize the object i posted. I can´t find an Angular serializer method, so I made my own(copy from another *** site) in JavaScript.
这是在使用 Angular2 & 时用户登录 API 并请求令牌时的最终调用.打字稿:
Here is the final call when the user login on the API and request a token, when using Angular2 & TypeScript:
loginAccount(account: Account): Observable<string> {
var obj = { UserName: account.Email, Password: account.Password, grant_type: 'password' };
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' });
let options = new RequestOptions( {method: RequestMethod.Post, headers: headers });
let body = this.serializeObj(obj);
return this._http.post('https://localhost:44305/Token', body, options)
.map(this.extractData)
.catch(this.handleError);
}
private serializeObj(obj) {
var result = [];
for (var property in obj)
result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));
return result.join("&");
}