class
Program
{
static
void Main(string[] args)
{
var
client =
new
HttpClient();
client.BaseAddress =
new
Uri(
"http://localhost:22658/"
);
client.DefaultRequestHeaders.Accept.Add(
new
MediaTypeWithQualityHeaderValue(
"application/json"
));
Run(client);
Console.ReadLine();
}
static
async void Run(HttpClient client)
{
var
result = await AddPerson(client);
Console.WriteLine($
"添加结果:{result}"
);
var
person = await GetPerson(client);
Console.WriteLine($
"查询结果:{person}"
);
result = await PutPerson(client);
Console.WriteLine($
"更新结果:{result}"
);
result = await DeletePerson(client);
Console.WriteLine($
"删除结果:{result}"
);
}
static
async Task<bool> AddPerson(HttpClient client)
{
return
await client.PostAsJsonAsync(
"api/Person"
,
new
Person() { Age = 10, Id = 1, Name =
"test"
, Sex =
"F"
})
.ContinueWith(x => x.Result.IsSuccessStatusCode);
}
static
async Task<Person> GetPerson(HttpClient client)
{
return
await await client.GetAsync(
"api/Person/1"
)
.ContinueWith(x => x.Result.Content.ReadAsAsync<Person>(
new
List<MediaTypeFormatter>() {
new
JsonMediaTypeFormatter()
,
new
XmlMediaTypeFormatter()
}));
}
static
async Task<bool> PutPerson(HttpClient client)
{
return
await client.PutAsJsonAsync(
"api/Person/1"
,
new
Person() { Age = 10, Id = 1, Name =
"test1Change"
, Sex =
"F"
})
.ContinueWith(x => x.Result.IsSuccessStatusCode);
}
static
async Task<bool> DeletePerson(HttpClient client)
{
return
await client.DeleteAsync(
"api/Person/1"
)
.ContinueWith(x => x.Result.IsSuccessStatusCode);
}
}