[HttpPut]
[ActionName("Index")]
public ActionResult Change()
{
return View();
}
MVC中的操作方法選擇將只允許你有最多2個的操作方法重載的同名方法。我明白你來自哪裏,希望只有{controller}/{id}作爲URL路徑,但你可能會以錯誤的方式解決它。
如果你只有2個控制器的操作方法,說1 GET和1 PUT,那麼你可以僅舉這兩個您的行爲指數,要麼像我一樣上面,或者是這樣的:
[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將不匹配前兩條路由,但會匹配第三條路由。
一旦MVC匹配路由,它將使用該路由定義的默認操作。所以當有人發送DELETE時,它將映射到控制器上的Delete方法。
您沒有顯示代碼如何實際配置路由,所以很難說如果您做錯了什麼。 –
謝謝阿列克謝,我已經添加了我的路由。 – Matthew
現在有道理 - 你有@danlundwig的回答 - 你的操作名稱「Index」在控制器中找不到。 –