我正在尝试向Asp.net MVC网站添加正确的路线。
这是我的路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("ShowProfile",
"Profile/{id}",
new { controller = "Profile", action = "Index" });
routes.MapRoute(
name:"Profile",
url: "{controller}/{action}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我的问题是,当我首先放置ShowProfile
路由时,它会正确显示配置文件但是当我输入www.example.com/profile/edit
时,它会显示错误Int
值,并且放置Profile
路由时首先显示www.example.com/profile/39
的404错误
我试图通过改变我的路线来解决这个问题:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("EditProfile",
"Profile/Edit",
new { controller = "Profile", action = "Edit" });
routes.MapRoute("ShowProfile",
"Profile/{id}",
new { controller = "Profile", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
以这种格式,它适用于这两种情况,但它显示404错误的其他发布方法,如:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditEmail()
{
return RedirectToAction("Index","Home");
}
但我不想为我的所有方法添加路由值,是否有任何一般方法可以不逐个添加路由值?
答案 0 :(得分:0)
您需要检查控制器。可能他们确实不包含返回HTTP404的这些操作。
这种方法适用于我,所有网址都有效:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Main()
{
return View();
}
}
public class ProfileController : Controller
{
public ActionResult Edit()
{
return View();
}
public ActionResult Show(int id)
{
@ViewBag.id = id;
return View();
}
}
路线:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("EditProfile",
"Profile/Edit",
new {controller = "Profile", action = "Edit"});
routes.MapRoute("ShowProfile",
"Profile/{id}",
new {controller = "Profile", action = "Show"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}