ASP MVC路由没有操作

我想在url中省略这个动作,因为我不认为这是一个宁静的方法。 默认路由应为:

"{controller}/{id}" 

然后调用与所使用的HTTP方法对应的操作。 例如,我正在装饰像这样的PUT动作:

 [HttpPut] public ActionResult Change() { return View(); } 

然而,当我说这个时,我得到了404.所以我做错了,之前有人试过这种方法吗?

我正在使用MVC4测试版。

这就是我正在做的设置路由:

  routes.MapRoute( name: "Default", url: "{controller}/{id}", defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional } ); 

 [HttpPut] [ActionName("Index")] public ActionResult Change() { return View(); } 

MVC中的操作方法选择器仅允许您对同名方法最多具有2个操作方法重载。 我知道你来自哪里,想要只有{controller} / {id}作为URL路径,但你可能会以错误的方式解决它。

如果您的控制器只有2个操作方法,比如说GET为1,PUT为1,那么您可以像上面一样命名两个操作索引,或者像这样:

 [HttpPut] public ActionResult Index() { return View(); } 

如果控制器上有两个以上的方法,则可以为其他操作创建新的自定义路由。 您的控制器可能如下所示:

 [HttpPut] public ActionResult Put() { return View(); } [HttpPost] public ActionResult Post() { return View(); } [HttpGet] public ActionResult Get() { return View(); } [HttpDelete] public ActionResult Delete() { return View(); } 

…如果你的global.asax看起来像这样:

 routes.MapRoute(null, "{controller}/{id}", // URL with parameters new { controller = "Home", action = "Get", id = UrlParameter.Optional }, new { httpMethod = new HttpMethodConstraint("GET") } ); routes.MapRoute(null, "{controller}/{id}", // URL with parameters new { controller = "Home", action = "Put", id = UrlParameter.Optional }, new { httpMethod = new HttpMethodConstraint("PUT") } ); routes.MapRoute(null, "{controller}", // URL with parameters new { controller = "Home", action = "Post", id = UrlParameter.Optional }, new { httpMethod = new HttpMethodConstraint("POST") } ); routes.MapRoute(null, "{controller}/{id}", // URL with parameters new { controller = "Home", action = "Delete", id = UrlParameter.Optional }, new { httpMethod = new HttpMethodConstraint("DELETE") } ); routes.MapRoute( "Default", // Route name "{controller}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 

…这些新的4条路由都有相同的URL模式,但POST除外(因为你应该POST到集合,但PUT到特定的id)。 但是,不同的HttpMethodConstraints只告诉MVC路由以匹配httpMethod对应的路由。 因此,当有人向/ MyItems / 6发送DELETE时,MVC将不匹配前3条路线,但将匹配第4条路线。 类似地,如果有人向/ MyItems / 13发送PUT,MVC将不匹配前2个路由,但将匹配第3个路由。

一旦MVC匹配路由,它将使用该路由定义的默认操作。 因此,当有人发送DELETE时,它将映射到控制器上的Delete方法。

考虑使用AttributeRouting nuget包。 它支持宁静的约定 。

如果您正在使用MVC4 Beta,为什么不使用WebAPI呢?

除此之外,我不认为路由引擎会查找各种HTTP动词…所以,你有点卡住了。 除非为所有这些方法重载单个Action方法并执行此操作:

 routes.MapRoute( "Default", // Route name "{controller}/{id}", // URL with parameters new { controller = "Home", action = "Restifier", id = UrlParameter.Optional } );