如何在 Web API C# 中传递单个对象而不是多个参数
How to pass single object instead of multiple parameters in Web API C#
在我的 Web API 应用程序中,我想通过多个条件来过滤掉数据库中的数据。这些条件将从 UI 开始传递。
string dateRangeType = "XYZ", string startDate = "", string endDate = ""
那么我如何将这 3 个参数组合成单个对象并在 Web API C#
中的 GET 方法中使用
在 Get 中不能传递单个对象,为此你需要将方法转换为 POST 方法。
WebApi 通过 FormFactory 和 JSON Factory 接受数据。这两个将请求数据转换为 post 的对象,而不是 GET。对于 GET,我们只需要与方法输入参数一样单一的参数。您还可以检查遵循相同方法的 Model Binder。
您可以在 class 中添加所有这 3 个属性,然后将该对象作为参数传递,然后 post 使用 body 的数据将完成这项工作
public class MyContract {
public string dateRangeType;
public string startDate;
public string endDate;
}
更改您的操作签名以将 MyContract
对象作为具有 [FromBody] 属性的参数传递,然后在您的请求正文中将数据作为 JSON 传递 -
{
dateRangeType: "abc",
startDate: "2017-09-10",
endDate: "2017-09-11"
}
您可以创建一个模型 class 并将其用作网络 api 控制器的参数。例如:
public class MyDateDTO
{
public String dateRangeType { get; set; }
public String startDate { get; set; }
public String endDate { get; set; }
}
下一个在您的网络 api 控制器中
[HttpGet]
public String MyDateAction([FromUri]MyDateDTO dto)//must put FromUri or else
//the web api action will try to read the reference type parameter from
//body
{
//your code
}
另请注意,您必须放置 FromUri 才能从查询参数中读取引用类型对象,因为默认情况下操作会尝试从正文中读取它。更多详情 here.
在我的 Web API 应用程序中,我想通过多个条件来过滤掉数据库中的数据。这些条件将从 UI 开始传递。
string dateRangeType = "XYZ", string startDate = "", string endDate = ""
那么我如何将这 3 个参数组合成单个对象并在 Web API C#
中的 GET 方法中使用在 Get 中不能传递单个对象,为此你需要将方法转换为 POST 方法。 WebApi 通过 FormFactory 和 JSON Factory 接受数据。这两个将请求数据转换为 post 的对象,而不是 GET。对于 GET,我们只需要与方法输入参数一样单一的参数。您还可以检查遵循相同方法的 Model Binder。
您可以在 class 中添加所有这 3 个属性,然后将该对象作为参数传递,然后 post 使用 body 的数据将完成这项工作
public class MyContract {
public string dateRangeType;
public string startDate;
public string endDate;
}
更改您的操作签名以将 MyContract
对象作为具有 [FromBody] 属性的参数传递,然后在您的请求正文中将数据作为 JSON 传递 -
{
dateRangeType: "abc",
startDate: "2017-09-10",
endDate: "2017-09-11"
}
您可以创建一个模型 class 并将其用作网络 api 控制器的参数。例如:
public class MyDateDTO
{
public String dateRangeType { get; set; }
public String startDate { get; set; }
public String endDate { get; set; }
}
下一个在您的网络 api 控制器中
[HttpGet]
public String MyDateAction([FromUri]MyDateDTO dto)//must put FromUri or else
//the web api action will try to read the reference type parameter from
//body
{
//your code
}
另请注意,您必须放置 FromUri 才能从查询参数中读取引用类型对象,因为默认情况下操作会尝试从正文中读取它。更多详情 here.