使用C#请求带Basic认证与表单编码的API令牌遇404问题
问题排查与解决方向
核心问题:请求URL错误
你代码中RestRequest的构造方式存在错误:
RestRequest request = new RestRequest("post", Method.Post);
第一个参数是相对资源路径,但你的baseurl已经包含了完整的令牌接口地址https://api address/token,这里传入"post"会让最终请求URL变成https://api address/token/post,和Postman中调用的地址完全不符,直接导致404 NotFound。
修正步骤
修正请求URL构造
将RestRequest的构造改为以下两种方式之一:// 方式一:直接指定请求方法 RestRequest request = new RestRequest(Method.Post); // 方式二:传入空字符串作为相对路径 RestRequest request = new RestRequest("", Method.Post);优化Basic认证方式(可选但更可靠)
手动拼接Authorization头容易出现编码不完整、字符串截断等问题,建议用RestSharp内置的Basic认证方法替代:// 替换手动添加Authorization头的代码 client.Authenticator = new HttpBasicAuthenticator("你的用户名", "你的密码");注:如果必须手动传头,务必确保
Basic后面的字符串是用户名:密码经过完整Base64编码后的结果,你当前的M2U4Y看起来像是截断值,这也可能是问题诱因。对齐Postman参数配置
检查scope参数的取值是否和Postman中完全一致,确保没有遗漏字符或拼写错误。
修正后的完整代码示例
private void button1_Click(object sender, EventArgs e) { Uri baseurl = new Uri("https://api address/token"); RestClient client = new RestClient(baseurl); // 推荐使用内置Basic认证,替代手动添加请求头 client.Authenticator = new HttpBasicAuthenticator("你的用户名", "你的密码"); RestRequest request = new RestRequest(Method.Post); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("grant_type", "client_credentials", true); request.AddParameter("scope", "https://正确的scope值", true); RestResponse response = client.Execute(request); if (string.IsNullOrEmpty(response.Content)) { textBox1.Text = response.ErrorException?.Message ?? "无响应内容"; } else { textBox1.Text = response.Content; } }
内容的提问来源于stack exchange,提问作者Sean ZA
相关产品推荐
相关产品推荐

