c# – 如何在GET请求中包含内容?
发布时间:2020-12-15 22:21:06 所属栏目:百科 来源:网络整理
导读:编辑:请注意,我知道问题的核心在于我需要与之通信的服务不遵循协议.这是我无法触及的软件,不会很快改变.因此,我需要帮助来规避问题并破坏协议.发展最好! 我正在尝试与外部服务进行通信.无论是谁决定将各种调用分成不同的文件夹,还有HTTP请求类型.这里的问
编辑:请注意,我知道问题的核心在于我需要与之通信的服务不遵循协议.这是我无法触及的软件,不会很快改变.因此,我需要帮助来规避问题并破坏协议.发展最好!
我正在尝试与外部服务进行通信.无论是谁决定将各种调用分成不同的文件夹,还有HTTP请求类型.这里的问题是我需要发送包含内容的GET请求. 是的,这违反了协议. 当我打电话时,它用异步方法包装.但是,发送它会导致错误:
电话代码: /// <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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |