i am trying to add a correct route to my Asp.net MVC website.
and here is my routes :
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 }
);
}
my problem is when i put ShowProfile
route first it shows profiles correctly but when i enter www.example.com/profile/edit
it show an error for missing Int
value and when putting Profile
route first an 404 error is shown for www.example.com/profile/39
.
i tried to fix this problem with changing my route to :
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 }
);
}
}
in this format it works fine for both situation but it shows an 404 error for other posting method like :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditEmail()
{
return RedirectToAction("Index","Home");
}
but i don't want to add a route value for all my methods , is there any general way for not adding one by one routing values ?
You need to check your controllers. Probably they really doesn't contain these actions that returns HTTP404.
This approach works well for me and all URLs works:
Controllers:
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();
}
}
Routes:
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}
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.