BaseAddress
BaseAddress у
HttpClient
по умолчанию null. Относительный
путь "abcde" превращается в
"http://abcde.example/abcde"
внутри заглушки без сети.
Синтаксис
client.BaseAddress = new Uri("http://abcde.example/");
Пример
Давайте проверить значение по умолчанию:
using System;
using System.Net.Http;
class Program
{
static void Main()
{
using HttpClient client = new HttpClient();
bool res = client.BaseAddress == null;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте прочитать AbsoluteUri базы:
using System;
using System.Net.Http;
class Program
{
static void Main()
{
using HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://abcde.example/");
string res = client.BaseAddress.AbsoluteUri;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"http://abcde.example/"
Пример
Давайте увидеть полный URI относительного запроса:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
public static string LastUri;
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
LastUri = request.RequestUri.AbsoluteUri;
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Program
{
static async Task Main()
{
using HttpClient client = new HttpClient(new Stub());
client.BaseAddress = new Uri("http://abcde.example/");
await client.GetAsync("abcde");
string res = Stub.LastUri;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"http://abcde.example/abcde"
Смотрите также
-
DefaultRequestHeaders,
заголовки по умолчанию -
GetAsync,
GET по URL -
SendAsync,
свой URI в сообщении -
HttpClient,
класс клиента