如何路由 API 并使用查询字符串?

How to route an API and use a query string?

我正在尝试制作一个 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 或常量?

我建议稍微改变一下。首先,您可以将路线模板更改得更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);
}

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