使用RestSharp进行API测试始终返回“Unauthorized Access, invalid API key”求助
Hey there, sorry you've been stuck on this for days—let's break down why your RestSharp call is throwing an "invalid API key" error when Postman works perfectly. Here are the most likely fixes to try:
1. Double-Check Your Authorization Header Format
A super common gotcha with Bearer tokens is forgetting the Bearer prefix. If your bearer variable only holds the raw token string (without that prefix), your header won't match what Postman sends. Update your header code to:
request.AddHeader("Authorization", $"Bearer {bearer}");
Verify this by checking Postman's Authorization tab—if it's set to "Bearer Token", the header value will definitely include that prefix.
2. Explicitly Specify Form Parameter Types
RestSharp's AddParameter can behave unpredictably depending on the request method, so explicitly marking your form fields ensures they're sent exactly like Postman does. Replace your parameter additions with either of these options:
Option A: Use GetOrPost Parameter Type
request.AddParameter("username", username, ParameterType.GetOrPost); request.AddParameter("password", password, ParameterType.GetOrPost); request.AddParameter("api_key", apiKey, ParameterType.GetOrPost);
Option B: Use AddFormParameter (RestSharp's dedicated form data method)
request.AddFormParameter("username", username); request.AddFormParameter("password", password); request.AddFormParameter("api_key", apiKey);
This guarantees your parameters are sent as application/x-www-form-urlencoded data, matching Postman's behavior perfectly.
3. Validate Your API Key Variable
It sounds obvious, but make sure your apiKey variable doesn't have hidden whitespace, typos, or case mismatches. Many APIs treat keys as case-sensitive—even one wrong character will trigger an error. Add a debug line to confirm:
Console.WriteLine("API Key being sent: '{0}'", apiKey); // The quotes help spot hidden spaces
Compare this directly to the key you're using in Postman—copy-paste the exact value into your code to rule out typos entirely.
4. Compare Request Details with Postman
The most definitive way to find the mismatch is to inspect the actual request your code sends vs. Postman's request. Here's how:
- In Postman, click the Code button (right next to "Send") and select "C# - RestSharp". This generates working RestSharp code—compare it line-by-line with your code to spot differences immediately.
- Alternatively, use a tool like Fiddler to capture both requests, then check:
- Header values (especially Authorization and Content-Type)
- Form parameter names and values
- Any extra headers Postman sends automatically (like User-Agent)
Updated Test Code Example
Here's a revised version of your method incorporating the above fixes, plus debug logging to help you spot issues:
[TestMethod] public void GetToken() { var client = new RestClient(baseUrl); // Add request logging to debug headers/parameters client.OnBeforeRequest = (req) => { Console.WriteLine("=== Request Headers ==="); foreach (var header in req.Parameters.Where(p => p.Type == ParameterType.HttpHeader)) { Console.WriteLine($"- {header.Name}: {header.Value}"); } Console.WriteLine("\n=== Form Parameters ==="); foreach (var param in req.Parameters.Where(p => p.Type == ParameterType.GetOrPost)) { Console.WriteLine($"- {param.Name}: {param.Value}"); } }; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); // Ensure Bearer prefix is included request.AddHeader("Authorization", $"Bearer {bearer}"); // Use dedicated form parameter method request.AddFormParameter("username", username); request.AddFormParameter("password", password); request.AddFormParameter("api_key", apiKey); IRestResponse restResponse = client.Execute(request); Console.WriteLine("\n=== Response ==="); Console.WriteLine("Status code: " + (int)restResponse.StatusCode); Console.WriteLine("Status message " + restResponse.Content); }
Start with comparing Postman's generated RestSharp code to yours—this will almost certainly reveal the exact mismatch causing the error. Good luck!
内容的提问来源于stack exchange,提问作者A.Singh

