【问题标题】:MapRoutes not working地图路线不起作用
【发布时间】:2013-07-18 14:00:39
【问题描述】:

我看不出这里出了什么问题。我在顶部有更具体的路线,但它只返回错误 404 - 未找到。

执行 /api/playernames/competitions 有效,但 /api/playernames/teams/competitionid/81bbd23d-54a2-4204-a771-85c48555a992 无效。我做错了什么?

routes.MapRoute("PlayerNamesDbTeams", "playernames/teams/competitionid/{competitionId}",
    new { controller = "playernames", action = "Teams", competitionId = "" });

routes.MapRoute("default", "{controller}/{action}/{id}", 
    new { controller = "playernames", action = "Competitions" });


public class PlayerNamesController : ApiController
{
    [HttpGet]
    public List<Competition> Competitions()
    {
        using (var service = new AggregatorClient())
        {
            return service.GetCompetitions();
        }
    }

    [HttpGet]
    public List<Team> Teams(string competitionId)
    {
        using (var service = new AggregatorClient())
        {
            return service.GetTeams(competitionId);
        }
    }
}

发出 /api/playernames/teams?competitionId=xxxxxx 之类的请求确实有效。

【问题讨论】:

  • 您是否对两个 URL 都进行了 GET 操作?
  • 是的......虽然我可能不确定你的意思。我已经声明它们是 HttpGet 方法。
  • /api/playernames/teams?competitionId=xxxxxx 确实有效
  • 我注意到它们在代码中被定义为 HttpGet - 我只是想检查当你得到 404 时你是否真的在做 GET 请求,仅此而已。
  • (例如,您没有在带有 POST 方法的表单中使用第二个 URL)

标签: c# asp.net-mvc rest asp.net-mvc-routing


【解决方案1】:

您似乎正在使用 MVC 路由;如果你使用 ApiControllers,你应该真正使用 WebApiConfig 来定义你的路由。

打开App_Start 文件夹中的WebApiConfig.cs 并按如下方式定义您的路线:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

config.Routes.MapHttpRoute(
    name: "PlayerNamesDbTeams",
    routeTemplate: "api/{controller}/{action}/competitionid/{competitionId}",
    defaults: new { competitionId = "" }
    );

【讨论】:

    猜你喜欢
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2013-05-03
    相关资源
    最近更新 更多