Cha*_*eus 20 javascript jquery asp.net-web-api angularjs asp.net-web-api2
我试着这样:
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password, grant_type: 'password' } }).success(function (data, status, headers, config) {
$scope.output = data;
}).error(function (data, status, headers, config) {
$scope.output = data;
});
Run Code Online (Sandbox Code Playgroud)
然后尝试将grant_type更改为param:
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password }, params: { grant_type: 'password' } }).success(function (data, status, headers, config) {
$scope.output = data;
}).error(function (data, status, headers, config) {
$scope.output = data;
});
Run Code Online (Sandbox Code Playgroud)
仍然可怕: {"error":"unsupported_grant_type"}
所以我做了AngularJS开发人员应该做的事情,使用jQuery:
var data = $('#regForm').serialize() + "&grant_type=password";
$.post('/token', data).always(showResponse);
function showResponse(object) {
$scope.output = JSON.stringify(object, null, 4);
$scope.$apply();
};
Run Code Online (Sandbox Code Playgroud)
这就像一个冠军...所以我的问题是:我们如何$.post()使用AngularJS 复制上面的jQuery 调用,$http()以便我们可以从ASP.Net Web API 2中的基于OWIN中间件/令牌端点获取访问令牌?
Ach*_*khi 19
做这个:
$http({
url: '/token',
method: 'POST',
data: "userName=" + $scope.username + "&password=" + $scope.password +
"&grant_type=password"
})
Run Code Online (Sandbox Code Playgroud)
zaf*_*s.m 18
我认为,将标题添加{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }到您的帖子请求中就可以了.它应该是这样的:
$http.post(loginAPIUrl, data,
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
Run Code Online (Sandbox Code Playgroud)
您收到该错误是因为OWIN OAuth提供程序的默认实现是期望对"/ Token"服务的帖子进行表单编码而不是json编码.这里有一个更详细的答案你如何设置katana-project以允许json格式的令牌请求?
但你仍然可以使用AngularJs,你只需要改变$ http帖子的制作方式.如果您不介意使用jquery更改参数,可以尝试这里的答案如何将数据作为表单数据而不是请求有效负载发布?希望有所帮助.
您始终可以使用浏览器中的开发人员控制台观察发出的请求,并查看请求中的差异。
但是通过查看您的 jquery 代码&grant_type=password是在正文中传递的,而不是查询字符串,因此$http调用应该是
$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password ,grant_type:password} }).success(function (data, status, headers, config) {