2017-08-07 34 views
2

我正在尝试制作一个API,它将根据您搜索的内容获取人员列表 - PhoneNumber,Email,Name如何路由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或恒定不知何故?

回答

1

我会建议改变一下。首先,您可以将路由模板更改为更加RESTful。接下来,您的卧底数据源可能会更具体一些。

//Matches GET ~/people/phone/123456789 
//Matches GET ~/people/email/[email protected] 
//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); 
} 

参考:Attribute Routing in ASP.NET Web API 2