我在集成测试中使用Flurl,并尝试配置客户端以记录响应(使用Flurl.Http 3.0.0)。
我正在使用事件处理程序将响应读取为字符串,然后将其记录。但是,如果调用代码在启用日志记录时使用IFlurlResponse.GetJsonAsync<>
,反序列化的对象将为null(我想是因为流已经被读取过了)。
我认为这可能是可能的,因为我可以看到Flurl内部跟踪响应流是否已被读取(使用_streamRead
和_capturedBody
成员)。
这是一个可重现的示例,使用Flurl.Http 3.0.0
:
class Program
{
static async Task Main(string[] args)
{
using (var client = new FlurlClient("https://jsonplaceholder.typicode.com/"))
{
var post = await client
.Request("posts/1")
.ConfigureRequest(settings => settings.AfterCallAsync = LogResponse)
.GetJsonAsync<Post>();
Console.WriteLine($"Is null with logging enabled: {post is null}"); // prints True
post = await client.Request("posts/1").GetJsonAsync<Post>();
Console.WriteLine($"Is null with logging disabled: {post is null}"); // prints False
}
}
private static async Task LogResponse(FlurlCall call)
{
var responseString = await call.Response.GetStringAsync();
Console.WriteLine(responseString);
}
}
public class Post
{
public int Id { get; set; }
public int UserId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
输出:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Is null with logging enabled: True
Is null with logging disabled: False
如果我将调用代码从使用GetJsonAsync<>
更改为GetStringAsync
并自己处理json反序列化,那么响应可以被“读取”两次,但这样会更加冗长。
LogResponse
中的实现?还是你在问其他的东西? - shack05