ASP.NET MVC3路由REST服务到控制器
本文关键字:服务 控制器 REST 路由 NET MVC3 ASP | 更新日期: 2023-09-27 17:54:17
我想按照以下方式路由REST服务url:
/User/Rest/ -> UserRestController.Index()
/User/Rest/Get -> UserRestController.Get()
/User/ -> UserController.Index()
/User/Get -> UserController.Get()
我在url中为Rest创建了一个硬编码异常
我不是很熟悉MVC路由。那么,实现这一目标的好方法是什么呢?
无论你在哪里注册你的路由,通常在global.ascx
routes.MapRoute(
"post-object",
"{controller}",
new {controller = "Home", action = "post"},
new {httpMethod = new HttpMethodConstraint("POST")}
);
routes.MapRoute(
"get-object",
"{controller}/{id}",
new { controller = "Home", action = "get"},
new { httpMethod = new HttpMethodConstraint("GET")}
);
routes.MapRoute(
"put-object",
"{controller}/{id}",
new { controller = "Home", action = "put" },
new { httpMethod = new HttpMethodConstraint("PUT")}
);
routes.MapRoute(
"delete-object",
"{controller}/{id}",
new { controller = "Home", action = "delete" },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);
routes.MapRoute(
"Default", // Route name
"{controller}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
,new[] {"ToolWatch.Presentation.API.Controllers"}
);
在控制器
public ActionResult Get() { }
public ActionResult Post() { }
public ActionResult Put() { }
public ActionResult Delete() { }