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
相关产品推荐
相关产品推荐

