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

C# Rest调用实现遇阻求助(附可用基础认证代码)

Hey there! Let's work through your REST call issue step by step. First, let's clean up and expand on the code you shared, then break down common pitfalls and fixes.

Your Current Code (Cleaned Up)

public async Task RunAsync(string name, string value) 
{ 
    using (var handler = new HttpClientHandler { UseDefaultCredentials = true }) 
    using (var client = new HttpClient(handler)) 
    { 
        var byteArray = Encoding.ASCII.GetBytes("username:password"); 
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); 
        var urlRestGet = HomeC... // Your URL is truncated here
        // Missing code to execute the request and handle the response
    }
}

Key Issues & Fixes

Let's address the most likely pain points you're hitting:

  1. Conflicting Authentication Methods
    You're enabling UseDefaultCredentials = true (which handles Windows integrated auth) and manually setting a Basic Auth header. These two can clash, causing the API to reject your credentials or pick the wrong auth method. Stick to one—since you're explicitly setting Basic Auth, remove the UseDefaultCredentials line.

  2. Incomplete URL & Request Execution
    Your urlRestGet is truncated, and there's no code to actually send the request. You need to finish building the URL (with proper parameter escaping!) and await an HTTP method like GetAsync or PostAsync.

  3. Missing Error Handling & Response Validation
    Async HTTP calls can fail silently if you don't check the response status or handle exceptions. Always validate success and catch common errors like network issues or 401/404 status codes.

Revised Working Example

public async Task RunAsync(string name, string value)
{
    // Skip UseDefaultCredentials since we're using explicit Basic Auth
    using (var handler = new HttpClientHandler())
    using (var client = new HttpClient(handler))
    {
        // Set up Basic Auth
        var credentials = "username:password";
        var byteArray = Encoding.ASCII.GetBytes(credentials);
        client.DefaultRequestHeaders.Authorization = 
            new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        // Build a valid, escaped URL (replace with your actual API endpoint)
        var baseUrl = "https://your-api-domain.com/api/resource";
        var urlRestGet = $"{baseUrl}?name={Uri.EscapeDataString(name)}&value={Uri.EscapeDataString(value)}";

        try
        {
            // Send the GET request and await the response
            var response = await client.GetAsync(urlRestGet);
            
            // Throw an exception if the response isn't a 2xx success code
            response.EnsureSuccessStatusCode();

            // Read and process the response content (adjust based on your API's return type)
            var responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Request succeeded! Response: " + responseContent);

            // If your API returns JSON, you can deserialize it here:
            // var resultObject = JsonSerializer.Deserialize<YourResponseType>(responseContent);
        }
        catch (HttpRequestException ex)
        {
            // Handle common errors (auth failures, missing endpoints, network issues)
            Console.WriteLine($"Request failed: {ex.Message}");
            if (ex.StatusCode.HasValue)
            {
                Console.WriteLine($"HTTP Status Code: {(int)ex.StatusCode.Value} - {ex.StatusCode.Value}");
            }
        }
    }
}

Bonus: If You Need to Send a POST Request

If your REST call requires sending data via POST instead of GET, use this snippet instead of the GetAsync section:

// Serialize your data to JSON (add using System.Text.Json;)
var requestBody = new { Name = name, Value = value };
var jsonContent = new StringContent(
    JsonSerializer.Serialize(requestBody),
    Encoding.UTF8,
    "application/json"
);

var postResponse = await client.PostAsync("https://your-api-domain.com/api/resource", jsonContent);
postResponse.EnsureSuccessStatusCode();
var postResponseContent = await postResponse.Content.ReadAsStringAsync();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:48:59