Postman发送Token请求正常,VS2022 C# POST请求返回Bad Request
问题分析与修复方案
你的C#代码存在两个关键问题,导致请求返回「Bad Request」:
1. 请求体格式错误
Postman中发送的是纯表单格式字符串(grant_type=password&username=TestUser&password=@Sep123456&scope=SepCentralPcPos openid),但你的代码错误地将其包装成JSON对象,再转成JSON字符串作为请求体,这和接口预期的application/x-www-form-urlencoded格式完全不符。
2. 缺失Authorization请求头
代码中注释掉了Authorization头的设置,而Postman请求里明确包含这个头,接口需要该认证信息才能正常处理请求。
修复后的代码
public async Task<string> GET_TOKEN() { try { // 直接使用表单格式字符串作为请求体,无需包装成JSON var formContent = "grant_type=password&username=TestUser&password=@Sep123456&scope=SepCentralPcPos openid"; using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(HttpMethod.Post, TokenAddress)) { // 添加Authorization认证头 request.Headers.TryAddWithoutValidation("Authorization", "Basic cm9jbGllbnQ6c2VjcmV0"); // 设置正确的请求体与Content-Type request.Content = new StringContent(formContent, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.SendAsync(request); // 主动抛出请求失败异常,便于调试排查 response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); JObject jsnResult = JsonConvert.DeserializeObject<JObject>(responseBody); string token = jsnResult["access_token"]?.ToString() ?? ""; long expiresIn = jsnResult["expires_in"]?.ToObject<long>() ?? 0; return token; } } } catch (Exception ex) { // 可添加日志记录,辅助排查异常 return ""; } }
额外优化建议
使用FormUrlEncodedContent更规范,它会自动处理特殊字符编码(比如密码中的@、scope中的空格),避免手动拼接字符串可能引发的格式错误:
var formData = new Dictionary<string, string> { {"grant_type", "password"}, {"username", "TestUser"}, {"password", "@Sep123456"}, {"scope", "SepCentralPcPos openid"} }; request.Content = new FormUrlEncodedContent(formData);
内容的提问来源于stack exchange,提问作者Esmail
相关产品推荐
相关产品推荐

