【问题标题】:How to send and receive Complex object in web api如何在 web api 中发送和接收复杂对象
【发布时间】:2016-03-01 07:51:35
【问题描述】:

IDE:Visual Studio 2012

我的控制器如下:

public class MyController: ApiController
{

  public IHttpActionResult AddMyControllerInfo([FromBody]Dictionary<string, string> dictCustomer)  
  {
     //Some logic...
      return Ok("Success");  
  }
}  

它是从客户端项目中调用的:

调用代码如下:

internal static void SendInfoToMyController(Dictionary<string, string> dictCustomer)
    {

        string jsDict = Utilities.SerializeToJson<Dictionary<string, string>>(dictCustomer);
        string js = Utilities.MakeRequest_Post("/api/AddMyControllerInfo", jsDict);

    }  

这里是Make请求函数:

internal static string MakeRequest_Post(string sURL, string formData)
    {
        try
        {

            sURL = ConfigurationManager.AppSettings["ServerApiPath"] + sURL;


            using (var client = new WebClient())
            {
                client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                var result = client.UploadString(sURL, "POST", "=" + formData);
            }
        }
        catch (Exception ex)
        {

        }
        return "";
    }  

当我以字符串(json 格式)数据类型的形式接收 [FromBody] 参数数据并将其反序列化为字典形式时,上述代码工作正常。

但在上述情况下,我将字典对象接收为 null。

你能告诉我如何在 web api 上接收复杂对象,对于上述场景。

【问题讨论】:

  • 是json字典格式。

标签: c# json asp.net-mvc http asp.net-web-api


【解决方案1】:

您在请求中使用了错误的内容类型。在您的 MakeRequest_Post 方法中,将内容类型标头更改如下:

client.Headers[HttpRequestHeader.ContentType] = "application/json";

我相信您还需要像这样从 POST 正文中删除前导 =

var result = client.UploadString(sURL, "POST", formData);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多