【问题标题】:Getting error: unsupported_grant_type using httpclient to post formdata in asp.net console app出现错误:unsupported_grant_type 使用 httpclient 在 asp.net 控制台应用程序中发布 formdata
【发布时间】:2019-12-18 11:01:15
【问题描述】:

我已经搜索了所有无济于事,仍然没有解决方案。 我正在尝试使用 asp.net 控制台应用程序和 httpclient 从第三方服务获取身份验证令牌。 在 Postman 中一切正常,但在 c# 中复制相同返回 "{\"error\":\"unsupported_grant_type\"}"

这是我的代码

 using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                var multiform = new MultipartFormDataContent()
                {
                    {new StringContent("password"), "grant_type" },
                    {new StringContent("adfadsasdfas"), "username" },
                    {new StringContent("asdfasdadf"), "password" },
                };

                var response = Task.Run(() => httpClient.PostAsync("http://localhost:61216/token", multiform)).Result;

                var message = Task.Run(() => response.Content.ReadAsStringAsync()).Result;

                if (!response.IsSuccessStatusCode)
                {
                    throw new HttpRequestException("Unable to post to cliams manager");
                }

            }

感谢期待... 抱歉,我已将 grant_type 更新为密码。这实际上不是 grant_type,因为“密码”也不起作用。

【问题讨论】:

  • 因为你设置了不正确的grant_type
  • 很难知道为什么。但是,如果这可以帮助您,有一种方法可以使用 Postman 生成代码。如果您单击代码按钮(在“保存”下的右侧
  • 同样的 grant_type 对 postman 有效,grant_type 不是真正的值

标签: c# asp.net httpclient


【解决方案1】:

问题似乎出在这部分代码上:

var multiform = new MultipartFormDataContent()
                {
                    {new StringContent("password"), "grant_type" },
                    {new StringContent("adfadsasdfas"), "username" },
                    {new StringContent("asdfasdadf"), "password" },
                };

你应该改用这个:

var content = new FormUrlEncodedContent(
    new KeyValuePair<string, string>[] {
        new KeyValuePair<string, string>("grant_type", "password"),
        new KeyValuePair<string, string>("username", "asdfsad"),
        new KeyValuePair<string, string>("password", "asdfaasdfa")
   }
);

【讨论】:

    【解决方案2】:

    在 OAuth 2 中,当我们发送用户 ID 和密码以检索访问令牌并且您发送的数据格式不正确时,我们将 grant_type 设置为“密码”您已将 Content-type 指定为 application/x-www-form-urlencoded但是您在POST 中发送multipart/form-data

    您可以在此处阅读有关密码授予类型的更多信息 https://www.rfc-editor.org/rfc/rfc6749#section-4.3.2

    【讨论】:

    • 已编辑问题,grant_type = "password" 在第一次尝试时也不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2011-03-27
    • 2010-10-27
    • 1970-01-01
    相关资源
    最近更新 更多