You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web API获取Token时unsupported_grant_type错误排查

问题原因及修正方案

你遇到的unsupported_grant_type错误,根源在于请求内容的格式和请求头设置不符合ASP.NET Web API Token端点的要求。

错误点分析

  • 请求体用username:user\npassword:1234\ngrant_type:password这种换行键值对格式,不是API要求的key=value用&分隔的表单格式。
  • 未设置请求内容的Content-Type头为application/x-www-form-urlencoded,导致API无法正确解析请求数据。

修正后的代码

private void TestButton_Click(object sender, EventArgs e)
{
    using (HttpClient httpClient = new HttpClient())
    {
        // 构造符合要求的表单数据
        var formData = new Dictionary<string, string>
        {
            { "username", "user" },
            { "password", "1234" },
            { "grant_type", "password" }
        };
        var content = new FormUrlEncodedContent(formData);

        HttpResponseMessage httpResponseMessage = httpClient
            .PostAsync(@"http://localhost:62986/Token", content).Result;

        richTextBox1.Text = string.Empty;
        richTextBox1.Text += ((int)httpResponseMessage.StatusCode).ToString() + "\n";
        richTextBox1.Text += httpResponseMessage.ReasonPhrase + "\n";
        richTextBox1.Text += httpResponseMessage.Content.ReadAsStringAsync().Result;
    }
}

关键修正说明

  • 使用FormUrlEncodedContent自动处理表单编码,同时自动设置Content-Type为application/x-www-form-urlencoded,无需手动拼接字符串。
  • 用using包裹HttpClient,确保资源正确释放(.NET Framework中局部使用时该写法更规范)。
  • 直接调用PostAsync简化代码,若需自定义更多请求头,也可保留HttpRequestMessage并将Content设置为FormUrlEncodedContent。

内容的提问来源于stack exchange,提问作者DotNet Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:20:22