First example
WebAPI:
[HttpPost]
public string Post(string value1, string value2)
{
return $"Sent: {value1}, {value2}";
}
Console:
Console.WriteLine("************* POST *************");
HttpClient httpClientPost = new HttpClient();
Task<HttpResponseMessage> httpResponseMessage = httpClientPost.PostAsync(@"https://localhost:7037/api/Values?value1=test1&value2=test2'", null);
Task<string> httpClientPostResult = httpResponseMessage.Result.Content.ReadAsStringAsync();
Console.WriteLine(httpClientPostResult.Result);
Example download from
here
---
Second example.
First install
Microsoft.AspNetCore.Mvc.NewtonsoftJson
In \WebApi\WebApi\Program.cs add line:
builder.Services.AddMvc().AddNewtonsoftJson();
Now Program.cs looks like:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddMvc().AddNewtonsoftJson();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Controller:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace WebApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// POST api/<ValuesController>
[HttpPost]
public string Post([FromBody] JObject data)
{
return "test";
}
}
Console:
using System.Text;
Console.WriteLine("************* POST *************");
HttpClient httpClientPost = new HttpClient();
Task<HttpResponseMessage> httpResponseMessage = httpClientPost.PostAsync(@"https://localhost:7037/api/Values"
, new StringContent(@"{""additionalProp1"":[""string""],""additionalProp2"":[""string""],""additionalProp3"":[""string""]}"
, Encoding.UTF8
, "application/json"));
Task<string> httpClientPostResult = httpResponseMessage.Result.Content.ReadAsStringAsync();
Console.WriteLine(httpClientPostResult.Result);
Taken from
here.
Example download from
here.