Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - httpclient call to webapi to post data not working

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Create a model

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; }
}

Then change you action, change de parameter type to MyModel

[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

Web API Controller and View Model

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 client application

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();
                }
            }
        }
    }
}

Output

Enter to continue

"JOHN"

Code output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...