【发布时间】:2016-10-11 15:04:25
【问题描述】:
当它被称为 /api/Games/aaa 时,我希望运行方法 Get(string deviceId = "")。但是当它被称为 api/Games/GameById/TaskId 我希望方法 GameById(int id) 被运行。但它不起作用,尤其是第二种方法。
控制器:
public class GamesController : ApiController
{
private List<Game> _gamesRepository;
public GamesController()
{
_gamesRepository = CreateGamesRepository();
}
// GET api/Games/DeviceId
[HttpGet]
public IEnumerable<Game> Get(string deviceId = "")
{
IEnumerable<Game> result;
if (String.IsNullOrEmpty(deviceId))
{
result = _gamesRepository.AsEnumerable();
}
else
{
result = _gamesRepository.Where(x => x.DeviceId == deviceId).AsEnumerable();
}
return result;
}
// GET api/Games/GameById/Id
[HttpGet]
public IEnumerable<Game> GameById(int id)
{
IEnumerable<Game> result;
result = _gamesRepository.Where(x => x.TaskId == id).AsEnumerable();
return result;
}
路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "GamesRoute",
url: "api/{controller}/{deviceId}",
defaults: new { controller = "controller", action = "get", deviceId = UrlParameter.Optional }
);
routes.MapRoute(
name: "GamesRoute2",
url: "api/games/GameById/{id}",
// defaults: new { id = UrlParameter.Optional }
defaults: new { controller = "games", action = "GameById" },
constraints: new { id = @"\d+" }
);
型号:
public class Game
{
public int TaskId { get; set; }
public string SalesForceId { get; set; }
public string Name { get; set; }
public string Thumbnail { get; set; }
public string DeviceId { get; set; }
}
}
【问题讨论】:
-
以下任何答案都回答了您的问题吗?
-
我不得不承认 :) ... 不 :)。我刚刚弄错了 2 个文件:RouteConfig 和 WebApiConfig :)。当我使用 webapiconfig 时,一切都按预期工作:)
-
您能否将您的解决方案作为答案发布或关闭您的问题(或在下面选择一个答案)?
标签: c# asp.net-mvc asp.net-web-api asp.net-web-api-routing