ASP MVC路由没有操作

问题描述 投票:3回答: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 }
    );
c# asp.net-mvc
3个回答
5
投票
[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对应的路由。因此,当有人将DELETE发送到/ MyItems / 6时,MVC将不匹配前3条路线,但会匹配第4条路线。类似地,如果有人向/ MyItems / 13发送PUT,MVC将不匹配前2个路由,但将匹配第3个路由。

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


2
投票

考虑使用AttributeRouting nuget包。它支持restful conventions


1
投票

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

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

routes.MapRoute(
  "Default", // Route name
  "{controller}/{id}", // URL with parameters
  new { controller = "Home", action = "Restifier", id = UrlParameter.Optional }
);
© www.soinside.com 2019 - 2024. All rights reserved.