Post request .Net 5.0

62 Views Asked by At

I’m trying to write a Post request in the custom function. In php can be written using CURL, What about dotnet? What’s the best way to convert the below code to .Net?

$header = array(
      'Authorization: Basic '. base64_encode(Key).’:’)
    );

    $curl = curl_init(‘URL’);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);
    $response = json_decode(curl_exec($curl), true);

I didn't have any experience in .net. I hope find the answer

Find a solution of send request use .net 5.0

1

There are 1 best solutions below

0
Tiny Wang On

.Net 5 is for web application and we have official document here.

Firstly, we need to inject http service into our project, which is the first step in the document doing. Adding services.AddHttpClient(); in the Startup.cs/ConfigureServices method which is used to inject IHttpClientFactory, so that we could use this http module in our main method.

Then in your method, you need to inject IHttpClientFactory into the constructor method.

public class YourClass
{
    private readonly IHttpClientFactory _clientFactory;


    public YourClass(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    
    public async Task YourMethod()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, "url");
        request.Headers.Add("Authorization", "Basic "+"your_custom_key");

        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            using var responseStream = await response.Content.ReadAsStreamAsync();
            var res = await JsonSerializer.DeserializeAsync<IEnumerable<JsonResponse>>(responseStream);//if the json response is a list
            //var res = await JsonSerializer.DeserializeAsync<JsonResponse>(responseStream);//if the json response is a object
        }
    }
}

public class JsonResponse{
    public string propertyOne{get; set;}
    public int propertyTwo{get; set;}
}