为什么我从Web API控制器上的Post方法获取空值?

时间:2015-10-16 12:07:53

标签: c# asp.net-web-api2

我有一个非常简单的WebAPI类,它为我的 Get 方法返回JSON。我的帖子方法是:

    // POST: api/Diff
    public void Post([FromBody]string value)
    {
        System.Diagnostics.Debug.WriteLine(value);
    }

我正在从控制台应用程序中调用这两种方法:

        using (var client = new HttpClient())
        {
            // New code:
            client.BaseAddress = new Uri("http://localhost:50541/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // New code:
            HttpResponseMessage response = await client.GetAsync("api/diff/1");
            if (response.IsSuccessStatusCode)
            {
                var diff = await response.Content.ReadAsAsync<Diff>();
                Console.WriteLine("{0}\t${1}", diff.Text, diff.Revision);
            }

            var blah = new Diff() { Text = "Gizmo", Revision = 999};
            response = await client.PostAsJsonAsync("api/diff", blah);

获取调用有效。我在调试器中验证过之前 调用PostAsJson方法, blah 不为null。但是,在API的post方法的调试器中, value 为空。

2 个答案:

答案 0 :(得分:2)

您向控制器发送一个复杂的对象:

var blah = new Diff() { Text = "Gizmo", Revision = 999};

但是你的控制器希望在请求的主体中只有一个名为“value”的字符串:

public void Post([FromBody]string value)

一种可能的解决方案是将Post方法的参数更改为Diff对象:

public void Post([FromBody]Diff diff)

答案 1 :(得分:2)

该方法需要string

public void Post([FromBody]string value)

你发送的是Diff

var blah = new Diff() { Text = "Gizmo", Revision = 999};
response = await client.PostAsJsonAsync("api/diff", blah);

因此...

要么将其更改为Diff

public void Post([FromBody]Diff value)

发送一个字符串:

response = await client.PostAsJsonAsync("api/diff", new { value = "some string" });