httpclient调用webapi进行数据提交不起作用

6
我需要进行一个简单的WebAPI调用,使用字符串参数的POST方法。
以下是我尝试的代码,但当在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)
{
}

please help...


1
"firstName" != "value" - Preston Guillot
3个回答

21

如果您想向Web API发送JSON,最好使用模型绑定功能,并使用类而不是字符串。

创建模型

public class MyModel
{
    [JsonProperty("firstName")]
    public string FirstName { get; set; }
}
如果您不想使用JsonProperty属性,可以像这样使用小写驼峰式编写属性。
public class MyModel
{
    public string firstName { get; set; }
}

然后更改您的操作,将参数类型更改为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"

代码输出


我尝试了这个..将WebAPI代码更改为上面的解决方案,客户端代码保持不变..但它仍然为null。我需要在客户端上做任何更改吗? - Harshini
@Harshini,我刚刚添加了一个带有输出的样本测试代码,请检查一下,看看与您实际的代码有什么不同。 - Alberto Monteiro
非常感谢您提供的代码。问题在于我把模型类放在了控制器里面,当我把它移出去之后,程序就正常工作了 :) - Harshini
非常有帮助。我遇到了同样的问题。非常感谢您,先生。这对我很有帮助。 - Unknown_Coder

1

备选答案:您可以将输入参数保留为字符串

[HttpPost]
public void Post([FromBody]string value)
{
}

使用C#的httpClient调用它,代码如下:

var kvpList = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);


string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
    try
    {   
        HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
        if (resp != null && resp.Content != null) {
            var result = await resp.Content.ReadAsStringAsync();
            //do whatevs with result
        } else
            //nothing returned.
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ResetColor();
    }
}

0

记录一下,我尝试了以上方法但无法让其工作!

我无法使其工作是因为我的API在一个单独的项目中。这没问题,对吧?不行,我正在控制器中进行依赖注入,同时使用Startup类针对Base项目。

您可以通过使用WebAPI的配置,在那里使用Unity进行配置依赖注入来解决此问题。以下代码适用于我:

WebApiConfig.cs:

 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            RegisterUnity();
        }

        private static void RegisterUnity()
        {
            var container = new UnityContainer();

            container.RegisterType<IIdentityRespository, IdentityRespository>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }

希望能对其他人有所帮助 :-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接