Home > Backend Development > C++ > How to POST String Values with .NET HttpClient?

How to POST String Values with .NET HttpClient?

DDD
Release: 2025-01-17 03:32:08
Original
707 people have browsed it

How to POST String Values with .NET HttpClient?

Sending String Data via .NET HttpClient POST Request

This guide demonstrates how to construct a POST request in C# using HttpClient to send string data, replicating the following request parameters:

Request Headers: User-Agent: Fiddler, Content-type: application/x-www-form-urlencoded, Host: localhost:6740, Content-Length: 6

The target is a WEB API endpoint with this method:

<code class="language-csharp">[ActionName("exist")]
[HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{
    return _membershipProvider.CheckIfExist(login);
}</code>
Copy after login

Implementation

The following C# code utilizes HttpClient to achieve this POST request:

<code class="language-csharp">using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await MainAsync();
        Console.ReadKey(); // Keep console window open until a key is pressed
    }

    static async Task MainAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new StringContent("login", System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
            var response = await client.PostAsync("/api/Membership/exists", content);
            string responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(responseContent);
        }
    }
}</code>
Copy after login

For ASP.NET 4.0 projects, remember to install the Microsoft.AspNet.WebApi.Client NuGet package before running this code. This ensures proper functionality with the HttpClient class.

The above is the detailed content of How to POST String Values with .NET HttpClient?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template