基本的MVC路由(模糊路由问题)

本文关键字:路由 模糊 问题 MVC | 更新日期: 2023-09-27 18:09:09

我的控制器上有3个动作,除了它们的参数之外,它们都不应该有路由。

[Route("")]
[HttpGet]
public ActionResult Index()
{
// List of things
    return View();
}
[Route("")]
[HttpGet]
public ActionResult Detail(int id)
{
// Specific 'thing'
    return View();
}
[Route("")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Detail(MyViewModel myViewModel)
{
// 'Thing' has just been posted
    return View();
}

当尝试调用第一个时,我得到一个"调用是模棱两可的"错误,第二个是404(即。"/区域/1001")。我应该如何在这里配置路由?

我想点击

  • Index() with '/area/'
  • Detail(int id) with '/area/123' and
  • Detail(MyViewModel MyViewModel)与post到'/area/'

编辑

我知道我可以将[Route("{id:int}")]添加到第二个动作中,但不确定第三个动作。

基本的MVC路由(模糊路由问题)

[RoutePrefix("Area")]
public AreaController : Controller {
    //GET Area
    [Route("")]
    [HttpGet]
    public ActionResult Index() {
        // List of things
        return View();
    }
    //GET Area/123
    [Route("{id:int}")]
    [HttpGet]
    public ActionResult Detail(int id) {
        // Specific 'thing'
        return View();
    }
    //POST Area
    [Route("")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Detail(MyViewModel myViewModel) {
        // 'Thing' has just been posted
        return View();
    }
}

确保你已经配置了属性路由

public static void RegisterRoutes(RouteCollection routes) {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
    //...other code
}