繁体   English   中英

来自PostAsync的HttpPost始终为null

[英]HttpPost from PostAsync always null

我将不知所措,试图弄清楚如何将POST参数传递给ASPNET CORE 2.0中的Web API方法。

我有一个C#客户端应用程序和一个C#服务器应用程序。

  • 我尝试在Web Api方法上使用[FromBody]。
  • 我尝试将内容类型设置为“ application / json”
  • 我已将控制器操作简化为尽可能基本
  • 我尝试传递一个字符串和一个复杂的对象。

总是为空。 到底是怎么回事?

客户代码

private static async Task SendCustomObject()
{
    var controllerName = "BasicApi";
    var basicClientApi = string.Format("http://localhost:5100/api/{0}", controllerName);

    using (var httpClient = new HttpClient()){

        var packetData = new TestPacket();
        var jsonObj = new { json = packetData };
        JObject jobject = JObject.FromObject(packetData);

        var json = JsonConvert.SerializeObject(jobject);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        // This doesn't help:
        //httpClient.DefaultRequestHeaders.Accept.Clear();
        //httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        var response = await httpClient.PostAsync(basicClientApi, content);                    

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var rawResponse = await response.Content.ReadAsStringAsync();                        

            JObject o = JObject.Parse(rawResponse);
            Console.WriteLine(o.ToString());    
        }
    }
}

服务器代码:

namespace myApp.Controllers
{
    [Route("api/[controller]")]
    public class BasicApiController : Controller
    {    

      [HttpPost]    
      public JsonResult Post([FromBody] string json) // json is always null!
      {                

        var jsonData = JsonConvert.DeserializeObject<Models.TestPacket>(json);
        return Json(new { result = true });

      }
    }
 }

ASP.NET Core默认活页夹为您反序列化模型,您无需手动完成。 具体来说,您不能将object视为string

看这个简单得多的例子:

private static async Task SendCustomObject()
{
    var controllerName = "BasicApi";
    var basicClientApi = string.Format("http://localhost:5100/api/{0}", controllerName);

    using (var httpClient = new HttpClient()){

        var packetData = new TestPacket();
        var jsonObj = new { json = packetData };

        var json = JsonConvert.SerializeObject(jsonObj); // no need to call `JObject.FromObject`
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await httpClient.PostAsync(basicClientApi, content);                    

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var rawResponse = await response.Content.ReadAsStringAsync();                        

            JObject o = JObject.Parse(rawResponse);
            Console.WriteLine(o.ToString());    
        }
    }
}

namespace myApp.Controllers
{
    [Route("api/[controller]")]
    public class BasicApiController : Controller
    {    

      [HttpPost]    
      // don't ask for a string, ask for the model you are expecting to recieve
      public JsonResult Post(Models.TestPacket json)
      {                
           return Json(new { result = true });
      }
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM