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

时间:2017-08-07 18:39:48

标签: c# api asp.net-web-api asp.net-web-api-routing

我正在尝试创建一个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 个答案:

答案 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);
}

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