【问题标题】:httpclient call to webapi to post data not workinghttpclient 调用 webapi 来发布数据不起作用
【发布时间】:2016-01-01 21:01:38
【问题描述】:

我需要使用字符串参数对 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)
{
}

请帮忙...

【问题讨论】:

  • "firstName" != "value"

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


【解决方案1】:

如果您想将 json 发送到您的 Web API,最好的选择是使用模型绑定功能,并使用类,而不是字符串。

创建模型

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# 类,请在此处查看此答案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 代码更改为上述解决方案,客户端代码保持不变..但它仍然为空。我需要更改客户端上的任何内容吗?
  • @Harshini 我刚刚在输出中添加了一个示例测试代码,检查它,看看与您的实际代码有什么不同。
  • 非常感谢你的代码。问题是我把模型类保存在控制器中。当我把它拿出来放出来的时候。它工作得很好:)
  • 非常有帮助。我坚持同样的问题。非常感谢先生。它对我有帮助。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    为了记录,我尝试了上述方法,但无法正常工作!

    我无法让它工作,因为我的 API 在一个单独的项目中。哪个好?不,我在对 Base 项目使用 Startup 类时对控制器进行依赖注入。

    您可以通过使用 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);
            }
        }
    

    我希望它可以帮助其他人:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      相关资源
      最近更新 更多