简体   繁体   English

如何在 F# 中记录 http 请求

[英]How to log http requests in F#

I have a F# console app (.Net 5) sending http requests via FSharp.Data and I haven't found a way to log the raw http requests.我有一个 F# 控制台应用程序(.Net 5)通过 FSharp.Data 发送 http 请求,但我还没有找到记录原始 http 请求的方法。 I tried using the F#.Net 6 web app template and enabling HttpLogging, but this won't log my http requests executed in the code.我尝试使用 F#.Net 6 web 应用程序模板并启用 HttpLogging,但这不会记录我在代码中执行的 http 请求。 Other tools like fiddler or wireshark are not an option because of work policies.由于工作政策,其他工具(如 fiddler 或 wireshark)不是一个选项。

Is there a way to enable such logging, for example in this minimal example console app?有没有办法启用这种日志记录,例如在这个最小的示例控制台应用程序中?

open FSharp.Data

[<EntryPoint>]
let main argv =
    let html = Http.Request("http://tomasp.net")
    printfn "%s" (html.ToString())
    0

You can pass a customization function to Http.Request, I think it would be OK to pass one that has a side effect of logging something about the request.您可以将自定义 function 传递给 Http.Request,我认为可以传递一个具有记录有关请求的副作用的副作用。 For example:例如:

open System.Net
open FSharp.Data

let requestHeaders =
    [
        "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
        "Accept", "*/*"
    ]

let requestCustomizeFunc =
    fun (request: HttpWebRequest) -> 
        printfn "Address: %O" request.Address
        printfn "Method: %O" request.Method
        printfn "Headers: %O" request.Headers
        request

[<EntryPoint>]
let main argv =
    let response = Http.Request ("http://tomasp.net", headers = requestHeaders, customizeHttpRequest = requestCustomizeFunc)

    response.StatusCode
    |> printfn "%O"

    0

This is quick and dirty;这又快又脏; if you're really serious about logging what's going on at the network level in your .NET app, you probably want to consider taking advantage of the built-in tracing capability.如果您真的很想在 .NET 应用程序中记录网络级别发生的事情,您可能需要考虑利用内置的跟踪功能。 See

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/network-tracing https://docs.microsoft.com/en-us/dotnet/framework/network-programming/network-tracing

That will be a bit more work.那将是更多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM