将POST参数传递给WEB API2

Dha*_*val 3 c# asp.net asp.net-web-api asp.net-web-api2

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

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

 public class patientRequest
 {
     public string str1 { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

所以为了得到工作,我创建了第3个模型,如下所示.

 public class patientMaster
 {
     patientRequest patientRequest;
     Authetication Authetication;
 }
Run Code Online (Sandbox Code Playgroud)

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

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


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

并抓住这个我在控制器中创建了以下方法

[HttpPost]
public string PostTestNew(patientMaster patientMaster)
{
   return " .. con .. ";
}
Run Code Online (Sandbox Code Playgroud)

我的问题是

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

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

有人可以帮我吗?

Ben*_*min 6

你非常接近.我添加了FromBody属性并指定了内容类型.我还可以patientMaster公开访问对象中的属性.

patientMaster对象:

 public class patientMaster
 {
    public patientRequest patientRequest { get; set;}
    public Authetication Authetication { get; set;}
 }
Run Code Online (Sandbox Code Playgroud)

API控制器:

[HttpPost]
public string PostTestNew([FromBody]PatientMaster patientMaster)
{
    return "Hello from API";
}
Run Code Online (Sandbox Code Playgroud)

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
});
Run Code Online (Sandbox Code Playgroud)