如果您想将 json 发送到您的 Web API,最好的选择是使用模型绑定功能,并使用类,而不是字符串。
创建模型
public class MyModel
{
[JsonProperty("firstName")]
public string FirstName { get; set; }
}
如果你不会使用JsonProperty属性,你可以用小写驼峰写属性,像这样
public class MyModel
{
public string firstName { get; set; }
}
然后更改您的操作,将 de 参数类型更改为 MyModel
[HttpPost]
public void Post([FromBody]MyModel value)
{
//value.FirstName
}
您可以使用 Visual Studio 自动创建 C# 类,请在此处查看此答案Deserialize JSON into Object C#
我做了以下测试代码
Web API 控制器和视图模型
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"