【问题标题】:How to automatically log responses using Flurl v3.0.0如何使用 Flurl v3.0.0 自动记录响应
【发布时间】:2020-11-13 02:57:56
【问题描述】:

我在集成测试中使用 Flurl 并尝试配置客户端以记录响应(使用 Flurl.Http 3.0.0)。

我正在使用event handlers 将响应读取为字符串,然后将其记录下来。 但是,如果在启用日志记录时调用代码使用IFlurlResponse.GetJsonAsync<>,则反序列化对象为空(我想是因为流已经被读取)。

我认为这是可能的,因为我可以看到 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&lt;&gt; 更改为 GetStringAsync 并自己处理 json 反序列化,则响应可以“读取”两次,但更冗长。

【问题讨论】:

  • 你能(至少)显示事件处理程序中发生了什么吗?
  • 我不确定我是否理解这个问题,我以为我在 LogResponse 中展示了实现?还是您要求别的?
  • ga,对不起,当我问这个问题时一定很累。不知道我怎么错过了。

标签: flurl


【解决方案1】:

更新fix 已成为 released


你说得对,在大多数情况下 Flurl “捕获”反序列化的响应,因此可以轻松地多次读取它们。但是,正如我认为您即将得出的结论,这目前仅在您反序列化为相同类型时才有效。如果事件处理程序和主逻辑都反序列化为string,或同时反序列化为Post,这应该可以工作。

我不确定我是否会完全称其为错误(也许?),但我确信让它按您所期望的那样工作将是一个很好的改进,而且不会太难。请打开issue,我会考虑在未来的版本中完成这项工作。

【讨论】:

  • 谢谢托德,我已经打开了issue 571
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多