将JSON发送到webapi控制器

时间:2016-08-19 20:23:59

标签: c#-4.0 json.net dotnet-httpclient

这似乎应该很容易。我需要将这样的数据发送到webapi控制器:

  

{       “startRace”: “2016-08-22T12:00:00.000Z”       “endRace”:“2016-08-26T12:00:00.000Z”}

所以我创建了一个控制台应用程序,这里是处理POST事件的代码片段:

        var i = (int)DateTime.Now.DayOfWeek;
        var startRace = DateTime.Today.AddDays(i);
        var endRace = DateTime.Today.AddDays(i + 4);


    var raceDates = new Dictionary<string, string>
                {
                    {"startRace", startRace.ToString("u")},
                    {"endRace", endRace.ToString("u")}
                };

        var json = JsonConvert.SerializeObject(raceDates);

        using (var http = new HttpClient())
        {
            try {

                 HttpResponseMessage response = http.PostAsync("http://localhost:15312/api/race/dates/post",
                   new StringContent(json, Encoding.UTF8, "application/json")).Result;

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

但每次我运行应用程序时,我总会收到此错误消息:

  

字符串不是JSON格式

我有什么遗失的吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个有效的示例代码。

控制台应用

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            var i = (int)DateTime.Now.DayOfWeek;
            var startRace = DateTime.Today.AddDays(i);
            var endRace = DateTime.Today.AddDays(i + 4);


            var raceDates = new Dictionary<string, string>
                {
                    {"startRace", startRace.ToString("u")},
                    {"endRace", endRace.ToString("u")}
                };

            var json = JsonConvert.SerializeObject(raceDates);

            using (var http = new HttpClient())
            {
                try
                {

                    HttpResponseMessage response = http.PostAsync("http://localhost:15312/api/race/dates/post/?raceDates=" + raceDates,
                      new StringContent(json, Encoding.UTF8, "application/json")).Result;

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

            }
        }
    }
}

Web API

using System.Collections.Generic;
using System.Web.Http;

namespace WebApplication1.Controllers
{

    public class RaceController : ApiController
    {

        [Route("api/race/dates/post")]
        public void Post(Dictionary<string, string> raceDates)
        {
            var dates = new Dictionary<string, string>
                {
                 {"startRace", raceDates["startRace"]},
                 {"endRace", raceDates["endRace"]}
            };

        }
    }
}