如何将json POST数据作为对象传递给Web API方法?


甲基蓝
2025-03-04 06:04:58 (3小时前)
  1. ASP.NET MVC4 Web


API
</跨度>
应用程序定义post方法来保存客户。
客户在POST请求正文中以json格式传递。
post方法中的customer参数包含属性null的空值。

如何解决这个问题,以便发布

数据
</跨度>
将作为客户对象传递?

如果可能的话Content-Type:application / x-www-form-urlencoded应该使用,因为我不知道如何在javascript方法中更改它

9 条回复
  1. 0# WL | 2019-08-31 10-32



    微软给出了一个很好的例子:




    https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1



    首先验证请求




    1. if (ModelState.IsValid)

    2. </code>


    而不是使用序列化数据。




    1. Content = new StringContent(update.Status)

    2. </code>


    这里的“状态”是复杂类型中的一个字段。序列化由.NET完成,无需担心。


  2. 1# 部落用户 | 2019-08-31 10-32



    在webapi中使用POST可能很棘手!
    想补充已经正确的答案..



    将专注于POST,因为处理GET是微不足道的。我不认为很多人会用webapis解决GET问题。无论如何..



    如果您的问题是 - 在MVC Web Api中,如何 - 使用除通用HTTP谓词之外的自定义操作方法名称? - 执行多个帖子? - 发布多个简单类型? - 通过jQuery发布复杂类型?



    那么以下解决方案可能有所帮助



    一,使用

    习惯
    </强>
    Web API中的操作方法,添加web api路由:




    1. public static void Register(HttpConfiguration config)
      {
      config.Routes.MapHttpRoute(
      name: ActionApi”,
      routeTemplate: api/{controller}/{action}”);
      }

    2. </code>


    然后你可以创建动作方法,如:




    1. [HttpPost]
      public string TestMethod([FromBody]string value)
      {
      return Hello from http post web api controller: + value;
      }

    2. </code>


    现在,从浏览器控制台激发以下jQuery




    1. $.ajax({
      type: POST’,
      url: http://localhost:33649/api/TestApi/TestMethod‘,
      data: {‘’:’hello’},
      contentType: application/x-www-form-urlencoded’,
      dataType: json’,
      success: function(data){ console.log(data) }
      });

    2. </code>


    第二,到

    执行多个帖子
    </强>
    ,它很简单,创建多个动作方法并使用[HttpPost] attrib进行装饰。使用[ActionName(“MyAction”)]分配自定义名称等。将在下面的第四点讨论jQuery



    第三,首先发布多个

    简单
    </强>
    单个操作中的类型是不可能的。
    而且,有一个

    特殊格式
    </强>
    甚至发布一个

    单一简单类型
    </强>
    (除了在查询字符串或REST样式中传递参数)。
    这就是让我与Rest Clients(如Fiddler和Chrome的高级REST客户端扩展)一起敲打头脑并在网上狩猎近5个小时的时间点,最终,以下网址被证明是有帮助的。会引用该链接的相关内容可能会变死!




    1. Content-Type: application/x-www-form-urlencoded
      in the request header and add a = before the JSON statement:
      ={“Name”:”Turbo Tina”,”Email”:”na@Turbo.Tina”}

    2. </code>


    PS:注意到了

    特有的语法




    <a href =“http://forums.asp.net/t/1883467.aspx?The+ceceived+value+is+null+when+I+try+to+Post+to+my+Web+Api"rel = “noreferrer”>
    http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api



    无论如何,让我们克服那个故事。继续:



    第四,

    发布复杂类型
    </强>
    通过jQuery,ofcourse,$ .ajax()将立即进入角色:



    我们假设action方法接受一个具有id和name的Person对象。所以,从javascript:




    1. var person = { PersonId:1, Name:”James }
      $.ajax({
      type: POST’,
      url: http://mydomain/api/TestApi/TestMethod‘,
      data: JSON.stringify(person),
      contentType: application/json; charset=utf-8’,
      dataType: json’,
      success: function(data){ console.log(data) }
      });

    2. </code>


    行动将如下所示:




    1. [HttpPost]
      public string TestMethod(Person person)
      {
      return Hello from http post web api controller: + person.Name;
      }

    2. </code>


    以上所有,为我工作!!干杯!


  3. 2# v-star*위위 | 2019-08-31 10-32



    使用

    JSON.stringify()

    获取JSON格式的字符串,确保在进行AJAX调用时传递下面提到的属性:




    • contentType:’application / json’


    • dataType:’json’



    下面是给jQuery的代码来调用asp.net web api的ajax:








    1. var product =
      JSON.stringify({
      productGroup: Fablet”,
      productId: 1,
      productName: Lumia 1525 64 GB”,
      sellingPrice: 700
      });

    2. $.ajax({
      URL: http://localhost/api/Products‘,
      type: POST’,
      contentType: application/json’,
      dataType: json’,
      data: product,
      success: function (data, status, xhr) {
      alert(‘Success!’);
      },
      error: function (xhr, status, error) {
      alert(‘Update Error occurred - + error);
      }
      });






  4. 3# 雪浴冰灵 | 2019-08-31 10-32



    确保您的WebAPI服务期望一个强类型对象,其结构与您传递的JSON相匹配。并确保您对要发布的JSON进行字符串化。



    这是我的JavaScript(使用AngluarJS):




    1. $scope.updateUserActivity = function (_objuserActivity) {
      $http
      ({
      method: post’,
      url: your url here’,
      headers: { Content-Type’: application/json’},
      data: JSON.stringify(_objuserActivity)
      })
      .then(function (response)
      {
      alert(“success”);
      })
      .catch(function (response)
      {
      alert(“failure”);
      })
      .finally(function ()
      {
      });

    2. </code>


    这是我的WebAPI控制器:




    1. [HttpPost]
      [AcceptVerbs(“POST”)]
      public string POSTMe([FromBody]Models.UserActivity _activity)
      {
      return hello”;
      }

    2. </code>

  5. 4# 烏鴉喝酒 | 2019-08-31 10-32




    以下代码以json格式返回数据,而不是xml -Web API 2: -
    </强>




    将以下行放在Global.asax文件中




    1. GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
      GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

    2. </code>

  6. 5# Hey ou | 2019-08-31 10-32



    1)在您的客户端,您可以发送http.post请求,如下所示




    1. var IndexInfo = JSON.stringify(this.scope.IndexTree);
      this.$http.post(‘../../../api/EvaluationProcess/InsertEvaluationProcessInputType’, “‘“ + IndexInfo + “‘“ ).then((response: any) => {}

    2. </code>


    2)然后在您的web api控制器中,您可以反序列化它




    1. public ApiResponce InsertEvaluationProcessInputType([FromBody]string IndexInfo)
      {
      var des = (ApiReceivedListOfObjects)Newtonsoft.Json.JsonConvert.DeserializeObject(DecryptedProcessInfo, typeof(ApiReceivedListOfObjects));}

    2. </code>


    3)您的ApiReceivedListOfObjects类应如下所示




    1. public class ApiReceivedListOfObjects
      {
      public List element { get; set; }

    2. }
    3. </code>


    4)确保在步骤2中的JsonConvert.DeserializeObject命令之前,序列化字符串(此处为IndexInfo)变为下面的结构




    1. var resp = @”
      {
      “”element””: [
      {
      “”A””: “”A Jones””,
      “”B””: “”500015763””
      },
      {
      “”A””: “”B Smith””,
      “”B””: “”504986213””
      },
      {
      “”A””: “”C Brown””,
      “”B””: “”509034361””
      }
      ]
      }”;

    2. </code>

  7. 6# 你咖喱人biss嗷 | 2019-08-31 10-32



    1. @model MVCClient.Models.ProductDetails

      @{
      ViewBag.Title = ProductDetails”;
      }


      ProductDetails





      ProductDetails



      @Html.LabelFor(model => model.ProductName)




      @Html.ValidationMessageFor(model => model.ProductName)
    2.     <div class="editor-label">
    3.         @Html.LabelFor(model => model.ProductDetail)
    4.     </div>
    5.     <div class="editor-field">
    6.         <input id="txt_desc" type="text" name="fname">
    7.         @Html.ValidationMessageFor(model => model.ProductDetail)
    8.     </div>
    9.     <div class="editor-label">
    10.         @Html.LabelFor(model => model.Price)
    11.     </div>
    12.     <div class="editor-field">
    13.         <input id="txt_price" type="text" name="fname">
    14.         @Html.ValidationMessageFor(model => model.Price)
    15.     </div>
    16.     <p>
    17.         <input id="Save" type="button" value="Create" />
    18.     </p>
    19. </fieldset>


    20. @Html.ActionLink(“Back to List”, Index”)

    21. @section Scripts {
      @Scripts.Render(“~/bundles/jqueryval”)
      }

    22. </code>

  8. 7# 时间 | 2019-08-31 10-32



    我刚刚玩这个并发现了一个相当奇怪的结果。假设您在C#中拥有公共属性,如下所示:




    1. public class Customer
      {
      public string contact_name;
      public string company_name;
      }

    2. </code>


    然后你必须按照Shyju的建议做JSON.stringify技巧,并像这样调用它:




    1. var customer = {contact_name :”Scott”,company_name:”HP”};
      $.ajax({
      type: POST”,
      data :JSON.stringify(customer),
      url: api/Customer”,
      contentType: application/json
      });

    2. </code>


    但是,如果您在类上定义getter和setter,如下所示:




    1. public class Customer
      {
      public string contact_name { get; set; }
      public string company_name { get; set; }
      }

    2. </code>


    然后你可以更简单地调用它:




    1. $.ajax({
      type: POST”,
      data :customer,
      url: api/Customer
      });

    2. </code>


    这使用HTTP标头:




    1. Content-Type:application/x-www-form-urlencoded

    2. </code>


    我不太确定这里发生了什么,但它看起来像框架中的一个错误(功能?)。据推测,不同的绑定方法调用不同的“适配器”,而应用程序/ json的适配器使用公共属性,而表单编码数据的适配器则不然。



    我不知道哪个被认为是最好的做法。


登录 后才能参与评论