我正在尝试创建一个API,根据您搜索的内容获取人员列表 - 电话号码,电子邮件,姓名
我的问题是我不知道如何路由API来做这样的事情......
[HttpGet, Route("SearchBy/{**searchByType**}/people")]
[NoNullArguments]
[Filterable]
public IHttpActionResult FindPeople([FromUri] string searchByType, object queryValue)
{
var response = new List<SearchSummary>();
switch (searchByType)
{
case "PhoneNumber":
response = peopleFinder.FindPeople((PhoneNumber)queryValue);
break;
case "Email":
response = peopleFinder.FindPeople((Email)queryValue);
break;
case "Name":
response = peopleFinder.FindPeople((Name) queryValue);
break;
}
return Ok(response);
}
我是否创建了一个SearchBy
对象并从中传递成员,或者以某种方式使用enum
或常量?
答案 0 :(得分:1)
我建议稍微改变一下。首先,您可以将路径模板更改为RESTful。接下来,您的底层数据源可能会在搜索时更加具体。
//Matches GET ~/people/phone/123456789
//Matches GET ~/people/email/someone@example.com
//Matches GET ~/people/name/John Doe
[HttpGet, Route("people/{searchByType:regex(^phone|email|name$)}/{filter}")]
[NoNullArguments]
[Filterable]
public IHttpActionResult FindPeople(string searchByType, string filter) {
var response = new List<SearchSummary>();
switch (searchByType.ToLower()) {
case "phone":
response = peopleFinder.FindPeopleByPhone(filter);
break;
case "email":
response = peopleFinder.FindPeopleByEmail(filter);
break;
case "name":
response = peopleFinder.FindPeopleByName(filter);
break;
default:
return BadRequest();
}
return Ok(response);
}