-1

我收到错误cannot send a content-body with this verb-type。我正在从 C# VSTO 桌面应用程序调用 GET Endpoint。我究竟做错了什么。

public static string GetCentralPath(LicenseMachineValidateRequestDTO licenseMachine)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization =    new AuthenticationHeaderValue("Bearer", Properties.Settings.Default.Properties["JWT"].DefaultValue.ToString());
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
            Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
        };
        
        using (HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult()) // Causing ERROR
        {
            var result = GetStringResultFromHttpResponseMessage(response, true);
            if (string.IsNullOrEmpty(result))
                return null;
            return JsonConvert.DeserializeObject<string>(result);
        }
    }
}

结束点如下所示:

[HttpGet("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)
{
    // Some code
}
4

1 回答 1

-1

修复操作,您无法使用 get 发送正文数据,请参阅这篇文章 HTTP GET with request body

[HttpPost("GetCentralPath")]
public async Task<IActionResult> GetCentralPath(LicenseMachineValidateRequestDTO dto)

并修复请求,将 Method = HttpMethod.Get 替换为 Post,这就是产生错误的原因

var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri($"{Constants.URL.APIBase}licensemachine/GetCentralPath"),
            Content = new StringContent(JsonConvert.SerializeObject(licenseMachine), Encoding.UTF8, "application/json"),
        };
于 2022-02-22T18:18:19.227 回答