【问题标题】:Get access token for web api using Jquery使用 Jquery 获取 Web api 的访问令牌
【发布时间】:2019-04-02 04:05:19
【问题描述】:

我有一个基于令牌的身份验证的 WEB API。当我使用 HTTP 客户端在控制台应用程序中发出请求时,它会正确执行。要执行的代码是

   var request = new HttpRequestMessage(HttpMethod.Post, apiBaseUrl + "token");
            var keyValues = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("grant_type", "client_credentials"),
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret)
            };
            request.Content = new FormUrlEncodedContent(keyValues);
            HttpClient httpClient = new HttpClient();
            var response = httpClient.SendAsync(request).Result;
            var result = response.Content.ReadAsStringAsync().Result;

我想使用 Ajax 发出相同的请求。但它显示了错误的请求。

    window.jQuery.ajax({
    "url": "http://localhost:63297/token",
    "type": "GET",
    "dataType": "json",
    "timeout": 10000,
    "data": {
        "client_id": "",
        "client_secret": "",
        "grant_type": "client_credentials"
    }
}).done(function(data, textStatus, jqxhr) {
    //Write code to be executed when the request SUCCEEDS.
}).fail(function(jqxhr, textStatus, errorThrown) {
    //Write code to be executed when the request FAILS.
});

【问题讨论】:

    标签: ajax rest asp.net-web-api access-token


    【解决方案1】:

    我认为您需要将 ajax 类型更改为 post 和 content 类型, contentType: 'application/x-www-form-urlencoded;字符集=UTF-8', 另请参阅以下问题以获取更多详细信息, Request Token with JQuery from Web API

    谢谢, Nagaraj M.

    【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2020-08-06
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多