【问题标题】:HttpPost from PostAsync always null来自 PostAsync 的 HttpPost 始终为空
【发布时间】:2018-06-30 10:12:34
【问题描述】:

我快要发疯了,试图弄清楚如何在 ASPNET CORE 2.0 中将 POST 参数传递给 Web API 方法。

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

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

它始终为 NULL。怎么回事?

客户端代码

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

      }
    }
 }

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

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

    【讨论】:

    • 如果我直接从客户端项目复制TestPacket.cs到服务端项目,binder会识别吗?我相信我已经尝试过了,但没有成功,但我会再试一次。
    • 哇。有效。我不知道为什么它现在可以工作而以前没有工作。我很确定我已经尝试过了。当您运行“dotnet build”时,VS Code 不会保存您的工作,所以也许我以为我测试了它,但实际上没有......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多