2017-08-07 68 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