Web Api 2中的unsupported_grant_type

时间:2016-07-29 10:29:02

标签: ajax authentication asp.net-web-api authorization asp.net-web-api2

我是Web Api的初学者并实施授权和身份验证,但是如下所述出现了一些错误:

从webApi

获取令牌时出现此错误
{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}

这是我的jQuery代码,用于请求令牌

$(document).ready(function () {
    $("#login").click(function () {
        debugger;
        var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
        console.log(details);
        $.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded",
            data: details,
            url: "http://localhost:59926/token",
            success: function (data) { console.log(JSON.stringify(data)); },
            error: function (data) { console.log(JSON.stringify(data)); }
        });
    });

2 个答案:

答案 0 :(得分:0)

contentType错了。它应该是application/json

$(document).ready(function () {
    $("#login").click(function () {
        debugger;
        var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
        console.log(details);
        $.ajax({
            type: "POST",
            contentType: "application/json",
            data: details,
            url: "http://localhost:59926/token",
            success: function (data) { console.log(JSON.stringify(data)); },
            error: function (data) { console.log(JSON.stringify(data)); }
        });
    });

答案 1 :(得分:0)

您的data应该类似于查询字符串,而不是JSON对象。如果需要,您应该对参数进行编码

data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'