Penguin Tech
Penguin Tech

Reputation: 73

Unable to do POST request using C# code using authentication

I am using below code to do a POST request on a url.

namespace ConsoleAppPost
{
    using System;
    using System.Net.Http;
    using System.Threading.Tasks;

    namespace HttpClientStatus
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                using var client = new HttpClient();

                var result = await client.PostAsync("https://XXXX/api/XXX/XX/XXX/xyz", HttpContent content);
                Console.WriteLine(result.StatusCode);


            }
        }
    }
}

But ,i am getting below error:

No overload for method PostAsync takes 1 argument

I also want to use username and password as authentication to do POST request in the code. Please help me.

Upvotes: 0

Views: 164

Answers (1)

KJSR
KJSR

Reputation: 1757

The issue lies here

var result = await client.PostAsync("https://XXXX/api/XXX/XX/XXX/xyz", HttpContent content);

You are passing type HttpContent content as parameter and NOT the data instead?

You need to do something like this

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("Username", "<value>"),
    new KeyValuePair<string, string>("Password", "<value>"),
});
var result = await client.PostAsync("https://XXXX/api/XXX/XX/XXX/xyz", content);

Upvotes: 1

Related Questions