3

我想省略 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 }
    );
4

3 回答 3

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

MVC 中的操作方法选择器只允许您最多有 2 个用于同名方法的操作方法重载。我了解您希望仅使用 {controller}/{id} 作为 URL 路径的来源,但您可能会以错误的方式进行操作。

如果您的控制器只有 2 个操作方法,例如 1 用于 GET,1 用于 PUT,那么您可以将两个操作命名为 Index,就像我在上面所做的那样,或者像这样:

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

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

[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 方法。

于 2012-05-31T19:27:49.533 回答
2

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

于 2012-05-31T19:31:59.170 回答
1

如果您使用的是 MVC4 Beta,为什么不也使用 WebAPI?

除此之外,我不认为路由引擎能理解各种 HTTP 动词......所以,你有点卡住了。除非您为所有这些重载一个 Action 方法并执行此操作:

routes.MapRoute(
  "Default", // Route name
  "{controller}/{id}", // URL with parameters
  new { controller = "Home", action = "Restifier", id = UrlParameter.Optional }
);
于 2012-05-31T19:23:13.247 回答