我正在尝试使用 C# 中的 PATCH API 并收到 http 400 bad request 错误。然而,相同的 API 正在工作并在 ReadyAPI 工具中返回 200 响应

问题描述 投票:0回答:2

我尝试使用 C# 访问 PATCH API 并收到 http 400 错误请求错误。然而,相同的 API 工作正常,并在 Ready API 工具中返回 http 200 响应。我尝试了 Stack Overflow 上的所有方法,但不确定我错过了什么。

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net;
using System.Text;
 
string apiUrl = "https://tfs.ups.com/tfs/UpsProd/P04S_SPPS/_apis/testplan/Plans/5150238/Suites/5716385/TestPoint?includePointDetails=true&returnIdentityRef=true";
string username = "******";
string password = "******";

var credentials = new NetworkCredential(username, password);
var handler = new HttpClientHandler { Credentials = credentials };

WebClient client1 = new WebClient();
client1.Encoding = Encoding.UTF8;
 
using (var client = new HttpClient(handler))
{
    try
    {
        client.BaseAddress = new Uri(apiUrl);
 
        string json = "[{\"id\":3490616,\"results\":{\"outcome\":2}}]"
        
        Console.WriteLine(json);
        var method = new HttpMethod("PATCH");
        client.DefaultRequestHeaders.Clear();
  
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
        client.DefaultRequestHeaders.TryAddWithoutValidation("api-version", "6.1-preview.2");

        byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(json);
        var content = new ByteArrayContent(messageBytes);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
             
        var response = client.PatchAsync(apiUrl, content).Result;

        Console.WriteLine(response.StatusCode);

        if (response.IsSuccessStatusCode)
        {
            Console.Write("Success");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}
c# .net tfs dotnet-httpclient patch
2个回答
1
投票

下面是我的 C# 代码示例,用于调用相同的 REST API,它可以正常工作。您可以参考它来编写您的 C# 代码。

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

. . .

var httpUri = "The complete HTTP Uri";
var reqMethod = "PATCH";
var reqPwd = "Personal Access Token";

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
    Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
        string.Format("{0}:{1}", "", reqPwd))));

var data = new[] {
    new {
        id = 12,
        results = new { outcome = 2 }
    }
};

HttpRequestMessage reqMsg = new HttpRequestMessage();
reqMsg.Method = new HttpMethod(reqMethod);
reqMsg.RequestUri = new Uri(httpUri);
reqMsg.Content = JsonContent.Create(data);

var reponse = client.SendAsync(reqMsg);
reponse.Wait();

var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
var jsonStr = JsonSerializer.Serialize(reponse.Result, jsonOptions);
Console.WriteLine(jsonStr);

0
投票

谢谢大家的评论和回答。 header 是这里的罪魁祸首。我没有单独传递标头,而是以这种方式传递标头并且它有效。 request.Headers.Add("接受", "application/json;api-version=6.1-preview.2;excludeUrls=true;enumsAsNumbers=true;msDateFormat=true;noArrayWrap=true");

© www.soinside.com 2019 - 2024. All rights reserved.