【问题标题】:Passing POST parameter to WEB API2将 POST 参数传递给 WEB API2
【发布时间】:2015-04-29 11:42:47
【问题描述】:

我有两个不同的模型需要传递给 web api。这两个样本模型如下

 public class Authetication
 {
     public string appID { get; set; }
 }

 public class patientRequest
 {
     public string str1 { get; set; }
 }

为了开始工作,我创建了第 3 个模型,如下所示。

 public class patientMaster
 {
     patientRequest patientRequest;
     Authetication Authetication;
 }

并传递我在 jquery 代码之后创建的数据

var patientMaster = { 
    patientRequest : { "str1" : "John" },                                       
    Authetication  : { "appID" : "Rick" } 
}


$.ajax({
          url: "http://localhost:50112/api/Patient/PostTestNew",
          type: "POST",
          data: {"": patientMaster}
        });

为了捕捉到这一点,我在控制器中创建了以下方法

[HttpPost]
public string PostTestNew(patientMaster patientMaster)
{
   return " .. con .. ";
}

我的问题是

每当测试我得到patientMaster对象但我没有得到任何数据Authetication对象或patientRequest对象

我也尝试在 jquery 中传递 contenttype:json 但它不起作用

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 尝试在 jQuery 函数的 data-property 中使用 exact 相同的名称作为 ActionResult。在这种情况下:data: {patientMaster : patientMaster}.
  • 试过了,但效果一样……得到了 patientMaster 对象,但我没有得到任何数据 Authetication 对象和 patientRequest 对象
  • 如果您将dataType: "json", 添加到您的ajax 调用中?
  • thn 也是同样的结果
  • 好的,如果你只是使用:data: patientMaster(但保留 dataType 等)。

标签: c# asp.net asp.net-web-api asp.net-web-api2


【解决方案1】:

你已经很接近了。我添加了一个FromBody 属性并指定了内容类型。我还将使您的 patientMaster 对象中的属性可公开访问。

patientMaster 对象:

 public class patientMaster
 {
    public patientRequest patientRequest { get; set;}
    public Authetication Authetication { get; set;}
 }

API 控制器:

[HttpPost]
public string PostTestNew([FromBody]PatientMaster patientMaster)
{
    return "Hello from API";
}

jQuery 代码:

var patientRequest = { "str1": "John" };
var authentication = { "appID": "Rick" };
var patientMaster = {
      "PatientRequest": patientRequest,
      "Authentication": authentication
};

$.ajax({
         url: "http://localhost:50112/api/Patient/PostTestNew",
         type: "POST",
         data: JSON.stringify(patientMaster),
         dataType: "json",
         contentType: "application/json",
         traditional: true
});

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    相关资源
    最近更新 更多