【发布时间】:2016-02-09 17:44:26
【问题描述】:
我已成功创建如下简单对象。
客户端js上的json如下。
{"Page":1, "Take":10, "SortOrder":"Asc", "PropName":"Id"}
在 webapi 方面,我有以下课程
public class PaginatedRequestCommand
{
public int Page { get; set; }
public int Take { get; set; }
public string PropName { get; set; }
public string SortOrder { get; set; }
}
而WebApiConfig类如下
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// skiped many other lines as they are not relevant
config.ParameterBindingRules.Insert(0, typeof(PaginatedRequestCommand),
x => x.BindWithAttribute(new FromUriAttribute()));
}
}
所以在 Wep Api 控制器中,我有以下操作方法。
[HttpPost]
[HttpGet]
public PaginatedList<PatientCategory> PatCat(PaginatedRequestCommand cmd)
{
//......
}
所以我在这里正确构造了 PaginatedRequestCommand 对象,并且属性 Page、Take 等是 正确可用。浏览器上的 Angularjs ajax 调用是
$http({
method: 'GET',
url: this.callParams.uri, // The URI
params: this.callParams.paginationOptions, // This is where the JSON that showed earlier goes.
headers: { 'Content-Type': 'application/Json' }
})
到目前为止,一切都很好。
现在我想传入更多参数。我想在 JSON 中包含一个数组,如下所示。
{"Page":1,"Take":10,"SortOrder":"Asc","PropName":"Id",
"wherePredicateParams":
[{"propName":"Name","val":"s"},
{"propName":"Description","val":"h"}
]
}
所以您看到“wherePredicateParams”是我要传递的附加对象。它是一个数组。 我需要在 WebApi 端进行哪些修改?
我尝试在 PaginatedRequestCommand 类中再添加一个属性 public string[] wherePredicateParams { get;放; } 所以全班如下。
public class PaginatedRequestCommand
{
public int Page { get; set; }
public int Take { get; set; }
public string PropName { get; set; }
public string SortOrder { get; set; }
public string[] wherePredicateParams { get; set; }
}
这实际上是有效的,因为 PaginatedRequestCommand 对象的属性 wherePredicateParams 由 api 在上述控制器的操作方法中创建
正在为我提供{"propName":"Name","val":"s"} 和{"propName":"Description","val":"h"}。但问题是我必须自己解析并使用它。有没有更好的办法。
然后我尝试将 string[] 更改为 whereParam[] 并定义了一个类
public class whereParam
{
public string propName { get; set; }
public string val { get; set; }
}
【问题讨论】:
标签: json asp.net-web-api