如何在C#中使用Flurl为GET请求添加请求体?
使用Flurl在C#中实现带请求体的GET请求
Flurl默认遵循HTTP规范,禁用了GET请求携带请求体的行为,但像Elasticsearch这类服务允许这种用法,以下是对应目标curl命令的实现方案:
1. 安装依赖包
确保项目中引入Flurl.Http:
# NuGet包管理器控制台 Install-Package Flurl.Http # 或.NET CLI命令 dotnet add package Flurl.Http
2. 实现请求代码
简化写法(直接获取JSON响应)
using Flurl.Http; using System.Net.Http; // 发送请求并直接解析为动态类型 var searchResult = await "http://localhost:9200/my-index-000001/_search" // 添加URL查询参数:from=40&size=20&pretty=true .SetQueryParams(new { from = 40, size = 20, pretty = true }) // 关键:解除Flurl对GET请求带请求体的限制 .AllowGetRequestBody() .WithHeader("Content-Type", "application/json") // 传入请求体并发送GET请求,自动序列化为JSON .GetJsonAsync<dynamic>(new { query = new { term = new { ["user.id"] = "kimchy" } } });
强类型响应写法(推荐)
如果需要强类型解析响应,先定义对应实体类:
using Newtonsoft.Json; public class ElasticsearchResponse { public HitsWrapper Hits { get; set; } } public class HitsWrapper { [JsonProperty("hits")] public Hit[] Items { get; set; } } public class Hit { [JsonProperty("_source")] public DocumentSource Source { get; set; } } public class DocumentSource { [JsonProperty("user.id")] public string UserId { get; set; } // 按需添加其他字段 }
再发送请求并解析:
var requestBody = new { query = new { term = new { ["user.id"] = "kimchy" } } }; var response = await "http://localhost:9200/my-index-000001/_search" .SetQueryParams(new { from = 40, size = 20, pretty = true }) .AllowGetRequestBody() .WithHeader("Content-Type", "application/json") .SendAsync(HttpMethod.Get, requestBody); var typedResult = await response.ReceiveJson<ElasticsearchResponse>();
关键说明
SetQueryParams:批量添加URL中的查询参数,替代手动拼接字符串AllowGetRequestBody():必须调用此方法,才能让Flurl允许GET请求携带请求体- Flurl会自动将匿名对象序列化为JSON格式,无需手动处理序列化逻辑
内容的提问来源于stack exchange,提问作者Mathieu Lecherbonnier
相关产品推荐
相关产品推荐

