gpt4 book ai didi

c# - 如何在 GET 请求中包含内容?

转载 作者:可可西里 更新时间:2023-11-01 15:29:31 25 4
gpt4 key购买 nike

编辑:请注意,我知道问题的核心在于我需要与之通信的服务未遵循协议(protocol)。这是我无法触及的软件,不会很快更改。因此,我需要帮助来规避问题和破坏协议(protocol)。最好的发展!

我正在尝试与外部服务通信。制作它的人决定将各种调用不仅拆分到不同的文件夹中,而且拆分到 HTTP 请求类型中。这里的问题是,我需要发送一个包含内容的 GET 请求。

是的,这违反了协议(protocol)。是的,如果我使用 Linux 命令制定调用,这会起作用。是的,如果我在 Fiddler 中手动创建调用(尽管 Fiddler 会对违反协议(protocol)的行为感到愤怒)

当我设计我的调用时,它被包裹在一个异步方法中。但是,发送它会导致错误:

Exception thrown: 'System.Net.ProtocolViolationException' in mscorlib.dll ("Cannot send a content-body with this verb-type.")

调用代码:

    /// <summary>
/// Gets a reading from a sensor
/// </summary>
/// <param name="query">Data query to set data with</param>
/// <returns></returns>
public async Task<string> GetData(string query)
{
var result = string.Empty;

try
{
// Send a GET request with a content containing the query. Don't ask, just accept it
var msg = new HttpRequestMessage(HttpMethod.Get, _dataApiUrl) { Content = new StringContent(query) };
var response = await _httpClient.SendAsync(msg).ConfigureAwait(false);

// Throws exception if baby broke
response.EnsureSuccessStatusCode();

// Convert to something slightly less useless
result = await response.Content.ReadAsStringAsync();
}
catch (Exception exc)
{
// Something broke ¯\_(ツ)_/¯
_logger.ErrorException("Something broke in GetData(). Probably a borked connection.", exc);
}
return result;
}

_httpClient 在构造函数中创建,是一个 System.Net.Http.HttpClient。

有没有人知道如何覆盖 HttpClient 的常规协议(protocol)并强制它以 GET 调用的形式进行调用,但内容包含我对服务器的查询?

最佳答案

对我来说,实现这一目标的破坏性较小的方法是将 Get KnownHttpVerbContentBodyNotAllowed 字段设置为 false使用反射。你可以试试这个:

public async Task<string> GetData(string query)
{
var result = string.Empty;
try
{
var KnownHttpVerbType = typeof(System.Net.AuthenticationManager).Assembly.GetTypes().Where(t => t.Name == "KnownHttpVerb").First();
var getVerb = KnownHttpVerbType.GetField("Get", BindingFlags.NonPublic | BindingFlags.Static);
var ContentBodyNotAllowedField = KnownHttpVerbType.GetField("ContentBodyNotAllowed", BindingFlags.NonPublic | BindingFlags.Instance);
ContentBodyNotAllowedField.SetValue(getVerb.GetValue(null), false);

var msg = new HttpRequestMessage(HttpMethod.Get, _dataApiUrl) { Content = new StringContent(query) };
var response = await _httpClient.SendAsync(msg).ConfigureAwait(false);
response.EnsureSuccessStatusCode();

result = await response.Content.ReadAsStringAsync();
}
catch (Exception exc)
{
_logger.ErrorException("Something broke in GetData(). Probably a borked connection.", exc);
}
return result;
}

关于c# - 如何在 GET 请求中包含内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32862655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com