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

C#中Get请求返回401未授权问题求助

Troubleshooting Your C# GET Request Authorization Issue

Let's work through why your authorization header works in Postman but fails in your C# code. Here are the most common fixes and checks to try:

1. Fix the Incomplete URL

Your current URI "myURL.com" is missing the required protocol (http:// or https://). Postman automatically fills this in, but C# requires a full, valid URL. Always include the protocol to avoid unexpected behavior:

string URI = "https://myURL.com"; // Add http/https prefix

2. Review the Content-Type Header

GET requests typically don't need a Content-Type header (since there's no request body). In your WebClient code, setting it to "text" is an invalid MIME type, which might confuse the server. Either remove this line entirely, or set it to the correct type if the server explicitly expects it (e.g., "application/xml" for XML responses):

// Remove this line unless the server specifically requires it
// wc.Headers.Add("Content-Type", "text");

3. Add Error Handling to Diagnose Exact Issues

Your current code doesn't catch exceptions, so you're missing critical details like 401 Unauthorized responses or server-side errors. Let's update both implementations with error handling to see what's going wrong:

Updated WebClient Implementation

public string Connect() {
    using (WebClient wc = new WebClient()) {
        string URI = "https://myURL.com";
        wc.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
        
        // Optional: Match Postman's User-Agent (some servers block default WebClient agents)
        wc.Headers[HttpRequestHeader.UserAgent] = "PostmanRuntime/7.32.3";

        try {
            return wc.DownloadString(URI);
        } catch (WebException ex) {
            if (ex.Response is HttpWebResponse response) {
                Console.WriteLine($"Error Status: {(int)response.StatusCode} - {response.StatusDescription}");
                // Read server error details for more context
                using (var reader = new StreamReader(response.GetResponseStream())) {
                    Console.WriteLine($"Server Error Details: {reader.ReadToEnd()}");
                }
            }
            throw; // Re-throw if you want to handle errors upstream
        }
    }
}

Updated HttpWebRequest Extension Method

public static string GetXml(this string destinationUrl) {
    // Ensure the URL has a valid protocol
    if (!destinationUrl.StartsWith("http://") && !destinationUrl.StartsWith("https://")) {
        destinationUrl = $"https://{destinationUrl}";
    }

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    request.Method = "GET";
    request.Headers[HttpRequestHeader.Authorization] = "Bearer OEMwNjI2ODQtMTc3OC00RkIxLTgyN0YtNzEzRkE5NzY3RTc3";
    request.UserAgent = "PostmanRuntime/7.32.3"; // Match Postman's agent to avoid blocks

    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            if (response.StatusCode == HttpStatusCode.OK) {
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream)) {
                    return reader.ReadToEnd();
                }
            } else {
                Console.WriteLine($"{response.StatusDescription} ({response.StatusCode})");
                return null;
            }
        }
    } catch (WebException ex) {
        if (ex.Response is HttpWebResponse errorResponse) {
            Console.WriteLine($"Request Failed: {(int)errorResponse.StatusCode} - {errorResponse.StatusDescription}");
            using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
                Console.WriteLine($"Server Error: {reader.ReadToEnd()}");
            }
        } else {
            Console.WriteLine($"Request Error: {ex.Message}");
        }
        return null;
    }
}

4. Compare Request Headers with Postman

Use a tool like Fiddler or Charles to capture HTTP traffic from both Postman and your C# code. Compare headers side-by-side to spot differences:

  • Missing headers (Postman might send extra headers like Accept that your code doesn't)
  • Differences in User-Agent (some servers block non-standard agents)
  • Typos in the authorization token (double-check for extra spaces or missing characters)

5. Other Quick Checks

  • Token Expiry: Confirm your Bearer token hasn't expired (even if Postman works, timing differences could cause this)
  • IP Whitelisting: The server might allow Postman's IP but block the machine running your C# code

With error handling added, you'll get specific details about why the request fails (e.g., 401 means the token is invalid, 403 might mean IP blocking). That will point you directly to the fix.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:56:53