httpclient调用webapi发布数据不起作用
我需要使用字符串参数对post方法进行简单的webapi调用。
下面是我正在尝试的代码,但是当在webapi方法上遇到断点时,接收的值为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);
和服务器端代码:
// POST api/values [HttpPost] public void Post([FromBody]string value) { }
请帮忙…
如果要将json发送到Web API,最好的选择是使用模型绑定function,并使用Class,而不是字符串。
创建一个模型
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#类,在此处查看此答案将JSON反序列化为对象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; } } }
Console客户端应用程序
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"