在阅读了很多答案后,我终于想通了。
首先,我在 WebApiConfig.cs 中添加了 3 个不同的路由
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
然后,从控制器函数中删除 ActionName、Route 等。所以基本上这是我的控制器;
// GET: api/Countries/5
[ResponseType(typeof(Countries))]
//[ActionName("CountryById")]
public async Task<IHttpActionResult> GetCountries(int id)
{
Countries countries = await db.Countries.FindAsync(id);
if (countries == null)
{
return NotFound();
}
return Ok(countries);
}
// GET: api/Countries/tur
//[ResponseType(typeof(Countries))]
////[Route("api/CountriesByName/{anyString}")]
////[ActionName("CountriesByName")]
//[HttpGet]
[ResponseType(typeof(Countries))]
//[ActionName("CountryByName")]
public async Task<IHttpActionResult> GetCountriesByName(string name)
{
var countries = await db.Countries
.Where(s=>s.Country.ToString().StartsWith(name))
.ToListAsync();
if (countries == null)
{
return NotFound();
}
return Ok(countries);
}
现在我可以使用以下 url 示例(带有名称和 id)运行;
http://localhost:49787/api/Countries/GetCountriesByName/France
http://localhost:49787/api/Countries/1