是否可以在同一路由中使用 2 种方法(GET 和 POST)?
Is it possible to have 2 methods (GET and POST) with the same route?
我想在我的控制器中有 2 个方法,它们具有相同的路由,但仅在 HTTP 方法上有所不同。具体来说,如果我的路线看起来像
routes.MapRoute(
name: "DataRoute",
url: "Sample/{user}/{id}/",
defaults: new { controller = "Sample", action = "--not sure--", user = "", id = "" }
);
我的控制器中有 2 个方法:
[HttpGet]
public void ViewData(string user, string id)
[HttpPost]
public void SetData(string user, string id)
如果我得到 Sample/a/b
,期望的行为是调用 ViewData()
,如果我 POST 到 Sample/a/b
,则调用 SetData()
,相同的 URL.
我知道我只能创建 2 条单独的路线,但出于设计原因,我希望一条路线仅由 GET
和 POST
区分。有没有办法配置路由或控制器来执行此操作而无需创建新路由?
使用属性路由,您应该能够使用不同的方法设置相同的路由。
[RoutePrefix("Sample")]
public class SampleController : Controller {
//eg GET Sample/a/b
[HttpGet]
[Route("{user}/{id}")]
public void ViewData(string user, string id) { ... }
//eg POST Sample/a/b
[HttpPost]
[Route("{user}/{id}")]
public void SetData(string user, string id) { ... }
}
不要忘记在基于约定的路由之前启用属性路由
routes.MapMvcAttributeRoutes();
您应该编辑 SetData
方法以从 POST 的正文中获取一些有效负载。
public void SetData(string user, string id, MyCustomObject data) { ... }
我想在我的控制器中有 2 个方法,它们具有相同的路由,但仅在 HTTP 方法上有所不同。具体来说,如果我的路线看起来像
routes.MapRoute(
name: "DataRoute",
url: "Sample/{user}/{id}/",
defaults: new { controller = "Sample", action = "--not sure--", user = "", id = "" }
);
我的控制器中有 2 个方法:
[HttpGet]
public void ViewData(string user, string id)
[HttpPost]
public void SetData(string user, string id)
如果我得到 Sample/a/b
,期望的行为是调用 ViewData()
,如果我 POST 到 Sample/a/b
,则调用 SetData()
,相同的 URL.
我知道我只能创建 2 条单独的路线,但出于设计原因,我希望一条路线仅由 GET
和 POST
区分。有没有办法配置路由或控制器来执行此操作而无需创建新路由?
使用属性路由,您应该能够使用不同的方法设置相同的路由。
[RoutePrefix("Sample")]
public class SampleController : Controller {
//eg GET Sample/a/b
[HttpGet]
[Route("{user}/{id}")]
public void ViewData(string user, string id) { ... }
//eg POST Sample/a/b
[HttpPost]
[Route("{user}/{id}")]
public void SetData(string user, string id) { ... }
}
不要忘记在基于约定的路由之前启用属性路由
routes.MapMvcAttributeRoutes();
您应该编辑 SetData
方法以从 POST 的正文中获取一些有效负载。
public void SetData(string user, string id, MyCustomObject data) { ... }