我正在使用 .NET 4.5 和 Web API 2(在 Visual Studio 2013 中)的最终版本。我一直在使用此文档作为参考,但无济于事。
我有一些基本路线,例如
api/providers
api/locations
api/specialties
还有一些方法喜欢
Get()
Get(int id)
Get(string keyword)
Autocomplete(string keyword)
Search(string zipcode, string name, int radius, [...])
理想情况下,我希望 URL 最终像
- /api/locations/12345(获取位置 12345)
- /api/locations/clinical(获取名称中带有“clinical”的位置)
- /api/locations/autocomplete?keyword=clinical (为名称中带有“clinical”的位置获取精简的 Id + Name 对象)
- /api/locations/search?zipcode=12345&radius=20&name=clinical (获取 zip 12345 20 英里范围内的位置,名称中包含“clinical”)
在下面的代码块中,Get
方法和Search
工作按预期工作,但Autocomplete
不是。应该注意的是,我在多个控制器中有类似命名的方法。我究竟做错了什么?(另外,这个属性到底是干什么Name =
用的?)
/// <summary>
/// This is the API used to interact with location information.
/// </summary>
[RoutePrefix("api/locations")]
public class LocationController : ApiController
{
private ProviderEntities db = new ProviderEntities();
private static readonly Expression<Func<Location, LocationAutocompleteDto>> AsLocationAutocompleteDto =
x => new LocationAutocompleteDto
{
Id = x.Id,
Name = x.Name
};
/// <summary>
/// Get ALL locations.
/// </summary>
[Route("")]
public IQueryable<Location> Get()
{
return db.Locations.AsQueryable();
}
/// <summary>
/// Get a specific location.
/// </summary>
/// <param name="id">The ID of a particular location.</param>
[Route("{id:int}")]
public IQueryable<Location> Get(int id)
{
return db.Locations.Where(l => l.Id == id);
}
/// <summary>
/// Get all locations that contain a keyword.
/// </summary>
/// <param name="keyword">The keyword to search for in a location name.</param>
[Route("{keyword:alpha}")]
public IQueryable<Location> Get(string keyword)
{
return db.Locations.Where(l => l.Name.Contains(keyword)).OrderBy(l => l.Name);
}
[Route("search", Name = "locationsearch")]
public string Search(string zipcode = null, string latitude = null, string longitude = null)
{
if (zipcode != null) return "zipcode";
if (latitude != null && longitude != null) return "lat/long";
else
return "invalid search";
}
/// <summary>
/// Autocomplete service for locations, returns simple Id/Name pairs.
/// </summary>
/// <param name="keyword">The keyword to search on.</param>
[Route("autocomplete/{keyword:alpha}", Name = "locationautocomplete")]
public IQueryable<LocationAutocompleteDto> Autocomplete(string keyword)
{
// validate the inputs
if (string.IsNullOrEmpty(keyword))
return null;
IQueryable<Location> results = from l in db.Locations
where l.Name.Contains(keyword)
select l;
return results.Select(AsLocationAutocompleteDto);
}
似乎还没有很多社区支持围绕这些东西的最新版本。
编辑(带答案)
简单替换
[Route("autocomplete/{keyword:alpha}", Name = "locationautocomplete")]
和
[Route("autocomplete"), Route("autocomplete/{keyword:alpha}", HttpGet()]
它工作得很好。