【问题标题】:HttpClient is sending NULL in web Api in mvc5HttpClient 在 mvc5 的 Web Api 中发送 NULL
【发布时间】:2017-12-08 07:49:47
【问题描述】:

HttpClient 在发布时向控制器发送空值,我的代码在这里请帮助我 .....................

using (HttpClient client=new HttpClient())
                    {


                            var parameters = ConvertToDictionary(tc);

                        client.BaseAddress = new Uri($"http://localhost:9797/");

                        var json = JsonConvert.SerializeObject(tc);
                        var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
                        var response = client.PostAsync(api_url, data).GetAwaiter().GetResult();
                        var k = JsonConvert.DeserializeObject<Api>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}

提前致谢

【问题讨论】:

    标签: post asp.net-web-api httpclient


    【解决方案1】:

    尝试在client.BaseAddress 中使用@insted of $。并检查 tc 对象是否不为空。 我用你的代码是这样的:

    class Program
    {
        static void Main(string[] args)
        {
            using (HttpClient client=new HttpClient())
            {
                client.BaseAddress = new Uri(@"http://localhost:61737/api/presidents");
    
                var json = JsonConvert.SerializeObject(new { name = "name", value = "value" });
                var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
                var response = client.PostAsync(@"http://localhost:61737/api/presidents/post", data).GetAwaiter().GetResult();
                var k = (response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
            }
        }
    }
    

    控制器看起来像这样:

    [RoutePrefix("api/presidents")]
    public class PresidentsController : ApiController
    {
        public class oooo
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }
        [Route("post")]
        public IHttpActionResult Post(oooo o)
        {
            return Ok(o);
        }
    }
    

    一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2011-09-01
      相关资源
      最近更新 更多