我可以使用在没有任何基本 URI 的情况下创建的
HttpClient
实例,并在 HttpRequestMessage
中添加所有详细信息以重用 HttpClient
实例。
class Example
{
private static readonly HttpClient client;
static Example()
{
client = new(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(15)
});
}
private void MakeHttpRequest() {
var httpRequestMessage = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = "www.example.com/uri"
};
var response = client.GetAsync(httpRequestMessage).Result;
//rest of the code
}
}
我怎样才能在
RestSharp
的 RestClient
中做到这一点。如何在 RestRequest
对象本身中发送完整的请求 URI?
RestRequest
构造函数似乎只是在寻找相对URI
/// <summary>
/// Constructor for a rest request to a relative resource URL and optional method
/// </summary>
/// <param name="resource">Resource to use</param>
/// <param name="method">Method to use (defaults to Method.Get></param>
public RestRequest(string? resource, Method method = Method.Get) : this() {
Resource = resource ?? "";
Method = method;
//rest of the code
}
您可以通过将
HttpClient
传递给 RestClient
构造函数来做到这一点。BaseUrl
否则它将无法工作。
var httpClient = new HttpClient();
var client = new RestClient(httpClient);
var request1 = new RestRequest("https://httpbin.org/status/200");
var response1 = client.Execute(request1);
Console.WriteLine(response1.StatusCode); //OK
var request2 = new RestRequest("https://postman-echo.com/status/201");
var response2 = client.Execute(request2);
Console.WriteLine(response2.StatusCode); //Created
Dotnet 小提琴:https://dotnetfiddle.net/Cg6wlh