编辑:请注意,我知道问题的核心在于我需要与之通信的服务不遵循协议.这是我无法触及的软件,不会很快改变.因此,我需要帮助来规避问题并破坏协议.发展最好!
我正在尝试与外部服务进行通信.无论是谁决定将各种调用分成不同的文件夹,还有HTTP请求类型.这里的问题是我需要发送包含内容的GET请求.
是的,这违反了协议.
是的,如果我使用Linux命令制定呼叫,这是有效的.
是的,如果我在Fiddler手动制作电话,这是有效的(尽管Fiddler对违反协议感到愤怒)
当我打电话时,它用异步方法包装.但是,发送它会导致错误:
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的常规协议并强制它将调用作为GET调用,但是内容包含我对服务器的查询?
最佳答案 对我来说,实现这一目标的破坏性较小的方法是使用反射将Get KnownHttpVerb的ContentBodyNotAllowed字段设置为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;
}