O
O
ohthatbaguk2021-04-11 16:00:59
Automation
ohthatbaguk, 2021-04-11 16:00:59

Get and Post using HttpClient in c#?

[Fact(DisplayName = "POST index.php?/api/v2/add_project when returns 200")]
        public async Task AddProject_WhenAddProject_ShouldReturnOK()
        {
            var client = Extensions.CreateHttpClient();
            
            var projectModel = AddProjectFactory.GetProjectModel();
            var json = JsonConvert.SerializeObject(projectModel);
            var data = new StringContent(json, Encoding.UTF8, "application/json");
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, "index.php?/api/v2/add_project");
            
            var response = await client.PostAsync("index.php?/api/v2/add_project", data);

            var result = await response.Content.ReadAsStringAsync();
            _testOutputHelper.WriteLine(PrettyJson(result));
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }


There is such a hard code, I can’t understand how I can make requests through requests more universal using SendAsync?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-04-11
@ohthatbaguk

Through Send it will be something like this:

var httpClient = new HttpClient();
var req = new HttpRequestMessage
{
    RequestUri = new Uri("index.php?/api/v2/add_project"),
    Method = HttpMethod.Get, // Вот тут
    Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
var response = httpClient.Send(req); // Можно и SendAsync использовать

L
Leonid Rozhnov, 2021-04-12
@Fulborg

Look towards the RestSharp library ( https://github.com/restsharp/RestSharp ). Significantly simplifies these operations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question