我想创建rest api,但我遇到路由问题。
这个网址没问题:localhost/project/controller/action/id
,但我也想要这个网址localhost/project/controller/id
。
例如:localhost/project/article/5
:ArticleController.Get(int id)
这是我的代码:
项目控制器
[HttpGet]
[Route("project/{id}")]
public JsonResult Get(int id)
{
}
路线配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Api",
url: "{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
当我调用url localhost / project / article / 5时,错误消息是在控制器'ArticleController'上找不到公共操作方法'5'。
哪里有问题?感谢
答案 0 :(得分:1)
您可以使用attribute routing
示例:强>
[HttpGet]
[Route("project/{controller}/{action}/{id}")]
public JsonResult Get(int id)
{
}
OR
示例:强>
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Api",
url: "project/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
根据您的要求,您的路由是:
[HttpGet]
[Route("project/article/{id:int}")]
public JsonResult Get(int id)
{
}
OR
routes.MapRoute(
name: "Api",
url: "project/article/{id}",
defaults: new { controller = "ArticleController", action = "Get", id = UrlParameter.Optional }
);