如何为 Web 请求指定 headers

How to specify headers for a web request

正在尝试为 http 调用设置 headers 但 运行 出现问题。 Authorization 和自定义 header x-api-key.

都需要指导
let url = "http://example.com"
let token = requestToken()

let request = WebRequest.Create(url) :?> HttpWebRequest
request.Method <- "GET"
request.Accept <- "application/json;charset=UTF-8"
request.Headers.Authorization <- sprintf "%s %s" token.token_type token.access_token
request.Headers["x-api-key"] <- "api-key" // custom headers

// or this

request.Headers["Authorization"] <- sprintf "%s %s" token.token_type token.access_token

我得到的错误是

error FS3217: This expression is not a function and cannot be applied. Did you intend to access the indexervia expr.[index] instead?

您收到的错误消息实际上告诉您问题出在哪里。在 F# 中,使用索引器的语法是 obj.[idx] - 您需要在对象和方括号之间有一个 .。在您的特定情况下正确的语法是:

request.Headers.["x-api-key"] <- "api-key"
request.Headers.["Authorization"] <- sprintf "%s %s" token.token_type token.access_token