I need to make a simple webapi call to post method with string argument.
Below is the code I'm trying, but when the breakpoint is hit on the webapi method, the received value is null
.
StringContent stringContent = new System.Net.Http.StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url.ToString(), stringContent);
and server side code:
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
please help...
Here, we will implement POST method in the Web API. The HTTP POST request is used to create a new record in the data source in the RESTful architecture. So let's create an action method in our StudentController to insert new student record in the database using Entity Framework.
The HTTP POST is usually used when you submit a web form or any HTTP data that can't be sent in the HTTP GET method. The HTTP POST is also used when uploading files to an HTTP server, e.g., uploading images to the HTTP server where the HTTP POST body contains one or more files.
If you want to send a json to your Web API, the best option is to use a model binding feature, and use a Class, instead a string.
public class MyModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
If you wont use the JsonProperty attribute, you can write property in lower case camel, like this
public class MyModel
{
public string firstName { get; set; }
}
[HttpPost]
public void Post([FromBody]MyModel value)
{
//value.FirstName
}
You can create C# classes automatically using Visual Studio, look this answer here Deserialize JSON into Object C#
I made this following test code
using System.Web.Http;
using Newtonsoft.Json;
namespace WebApplication3.Controllers
{
public class ValuesController : ApiController
{
[HttpPost]
public string Post([FromBody]MyModel value)
{
return value.FirstName.ToUpper();
}
}
public class MyModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
}
using System;
using System.Net.Http;
namespace Temp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter to continue");
Console.ReadLine();
DoIt();
Console.ReadLine();
}
private static async void DoIt()
{
using (var stringContent = new StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json"))
using (var client = new HttpClient())
{
try
{
var response = await client.PostAsync("http://localhost:52042/api/values", stringContent);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
}
}
}
Enter to continue
"JOHN"
Alternative answer: You can leave your input parameter as string
[HttpPost]
public void Post([FromBody]string value)
{
}
, and call it with the C# httpClient as follows:
var kvpList = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);
string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
try
{
HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
if (resp != null && resp.Content != null) {
var result = await resp.Content.ReadAsStringAsync();
//do whatevs with result
} else
//nothing returned.
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With