我在我的网站上设置了以下区域。
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"AdminDefaultNoAction",
"Admin/{controller}/{id}",
new { action = "Home", id = UrlParameter.Optional }, new[] { "DevTest.Areas.Admin.Controllers" }
);
context.MapRoute(
"AdminDefault",
"Admin/{controller}/{action}/{id}",
new { action = "Home", id = UrlParameter.Optional }, new[] { "DevTest.Areas.Admin.Controllers" }
);
}
}
以及我的控制器中的以下方法。
public class PlayerController : Controller
{
public PlayerController()
{
}
[HttpGet]
public ActionResult Home(Guid id)
{
var model = new HomeViewModel();
// Do Stuff
return View("Home", model);
}
[HttpPost]
public ActionResult Home(HomeViewModel model)
{
// Do Stuff
return View("Home", model);
}
public ActionResult TestMethod(Guid id)
{
return Json(new
{
Test = "Hi!",
id = id.ToString()
});
}
}
我的两种家庭方法工作正常。如果我用 Admin/Player/TestMethod/e0ef4ab3-3fe5-4ea8-8ae1-c16b9defcabe 击中它,测试方法可以工作,但如果我用 Admin/Player/TestMethod?id=e0ef4ab3-3fe5-4ea8-8ae1-c16b9defcabe 击中它,则失败。
这显然只是一个示范性的例子。我希望能够在此控制器中命中一些方法,传入值(主要通过 ajax 请求),但路由未按预期工作。
提前谢谢。
正如@Stephen Muecke在评论中指出的那样,我的第一条路线不够具体。我必须将 id 限制为一个 guid,以便它按预期工作。
我用正则表达式做了这件事,因为我仍在使用 Mvc 版本 4。
context.MapRoute(
"AdminDefaultNoAction",
"Admin/{controller}/{id}",
new { action = "Home", id = UrlParameter.Optional },
new { id = @"[a-f0-9-]+" },
new[] { "DevTest.Areas.Admin.Controllers" }
);
如果我有 Mvc 5,我可以使用:
new { guid = new GuidRouteConstraint() }