I'm working in MVC 5 and have taken over a project. When I log onto the homepage "mydomain.com" it comes up with an error:
"Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. Requested URL:/"
If I type in mydomain.com/home/index it comes up with the home page as it should. I figure this is a RouteConfig.cs problem, but everything looks pretty default to me.
namespace Source
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Glossary2",
url: "{controller}/{action}/{letter}",
defaults: new { controller = "Teacher", action = "Glossary2", letter = UrlParameter.Optional }
);
/* Will need to finish this later.
* When the contact us form is submitted, it should redirect to Home/Contact/{state}
* where {state} can be either 'Success' or 'Error', which will display
* an alert component in the view based on the provided {state}.
*/
routes.MapRoute(
name: "ContactSuccess",
url: "{controller}/{action}/{submissionStatus}",
defaults: new { controller = "Home", action = "Contact", submissionStatus = UrlParameter.Optional }
);
/* Will need to finish this later.
* When the contact us form is displayed, it should check to see if a reason for contacting
* us is already set. If it is, it should automatically select the appropriate reason on the
* dropdown menu.
*/
routes.MapRoute(
name: "ContactReason",
url: "{controller}/{action}/{reason}",
defaults: new { controller = "Home", action = "Contact", reason = UrlParameter.Optional }
);
}
}
}
I'm not sure what the CustomeViewEngine is doing and haven't really messed around with it yet. I've also inspected the Global.asax.cs file and it looks pretty standard as well.
namespace Source
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Add(new CustomViewEngine());
}
}
public class CustomViewEngine : RazorViewEngine
{
public static readonly string[] CUSTOM_PARTIAL_VIEW_FORMATS = new[]
{ "~/Views/Selection/{0}.cshtml" };
public CustomViewEngine()
{
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(CUSTOM_PARTIAL_VIEW_FORMATS).ToArray();
}
}
}
Is there a way to trace down why the domain name is not getting routed to home/index? If I put the Default mapping at the bottom of the RouteConfig file it wants to automatically direct to the login page. Again, I'm not really understanding why this would be acting this way.
I think your route definitions are not in right order, the route order evaluates from top to bottom (the most specific path resolved first).
Hence, the default route should be take place as the last defined route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// custom path at the top (or top-most depending on priority)
routes.MapRoute(
name: "Example",
url: "Example/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
// default path at the bottom-most
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Additionally, all URLs defined in every route in the sample are in same pattern (using {controller}/{action}/{parameter}), hence it potentially conflict between each other. You can use plain strings to differentiate similar route patterns:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Glossary2",
url: "Teacher/{action}/{letter}",
defaults: new { controller = "Teacher", action = "Glossary2", letter = UrlParameter.Optional }
);
routes.MapRoute(
name: "ContactSuccess",
url: "{controller}/{action}/SubmissionStatus/{submissionStatus}",
defaults: new { controller = "Home", action = "Contact", submissionStatus = UrlParameter.Optional }
);
routes.MapRoute(
name: "ContactReason",
url: "{controller}/{action}/Reason/{reason}",
defaults: new { controller = "Home", action = "Contact", reason = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note: Use RouteDebugger to find out which routes handled by RouteConfig when accessing specific routes.
Related
I am kinda blocked with some routing issues in my ASP.NET MVC application.
Let us assume I have 2 controllers which are:
TaskList Controller
Task Controller
I'm not sure if this is overkill or not but I am aiming to have URL's as follows:
For TaskList Controller:
localhost:xxxx/tasklist/Create
localhost:xxxx/tasklist/
localhost:xxxx/tasklist/Details/1
localhost:xxxx/tasklist/Edit/1
For Task Controller:
localhost:xxxx/tasklist/1/Task/Create
localhost:xxxx/tasklist/1/Task
localhost:xxxx/tasklist/1/Task/Details/11
localhost:xxxx/tasklist/1/Task/Edit/11
I have set up my routing as follows:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "TaskListRoute",
url: "TaskList/{action}/{tasklistid}",
defaults: new { controller = "TaskList", action = "Index", tasklistid = UrlParameter.Optional }
);
routes.MapRoute(
name: "TaskRoute",
url: "TaskList/{tasklistid}/{controller}/{action}/{taskid}",
defaults: new { tasklistid = UrlParameter.Optional, controller = "Task", action = "Index", taskid = UrlParameter.Optional }
);
Upon debugging the application, I am able to browse the TaskList controller with no problems but the moment I hit the following url on the Task Controller, I get a "Resource cannot be found" error:
http://localhost:xxxx/tasklist/1/Task
I have to type in the word "Index" like below in order for that page to work...
http://localhost:xxxx/tasklist/1/Task/Index
The method signature behind the above url is...
public class TaskController : Controller
{
// GET: Task
public ActionResult Index(int tasklistid)
{
//Some code here....
}
}
Any ideas where I wrong? Appreciate any advice.
Thanks in advance.
So after taking Nkosi's comment and NightOwl888's article into consideration all I had to do was modify the routing to look like the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "TaskRoute",
url: "TaskList/{tasklistid}/Task/{action}/{taskid}",
defaults: new { controller = "Task", action = "Index", taskid = UrlParameter.Optional }
);
routes.MapRoute(
name: "TaskListRoute",
url: "TaskList/{action}/{tasklistid}",
defaults: new { controller = "TaskList", action = "Index", tasklistid = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
Basically did the following:
Adjust routing to be in following order:
TaskRoute
TaskListRoute
Default
In the TaskRoute, replaced '{controller}' with a literal like 'Task'
which is actually the name of the controller.
I hope this was the right thing to do.
Cheers
I would like to create a dynamic routing to a URL like following:
http://localhost:51577/Item/AnyActionName/Id
Please note that the controller name is static and doesn't need to be dynamic. On the other hand, I need to have the action name part dynamic so that whatever is written in that part of URL, I would redirect the user to the Index action inside of Item controller.
What I have tried so far is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Items",
"Item/{action}/{id}",
new { controller = "Item", action = "Index", id = UrlParameter.Optional });
}
And when I build my app I get a following error:
The resource cannot be found.
Edit:
Here is my Global.asax file and the routeconfig.cs file:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
And here's the content of the RouteConfig.cs file with the answer that #Nkosi provided:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Items",
url: "Item/{id}/{*slug}",
defaults: new { controller = "Item", action = "Index", slug = UrlParameter.Optional }
);
}
}
What you are referring to in your question is called a slug.
I answered a similar question here for web api
Web api - how to route using slugs?
With the slug at the end the route config would look like this
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Items",
url: "Item/{id}/{*slug}",
defaults: new { controller = "Item", action = "Index", slug = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
which could match an example controller action...
public class ItemController : Controller {
public ActionResult Index(int id, string slug = null) {
//...
}
}
the example URL...
"Item/31223512/Any-Item-Name"
would then have the parameters matched as follows...
id = 31223512
slug = "Any-Item-Name"
And because the slug is optional, the above URL will still be matched to
"Item/31223512"
I have a website developed in dot net 2.0 I need to update that in to MVC framework. How to keep my old URLs same in MVC? For eg. WWW.something.com/Home.aspx and WWW.something.com/About.aspx. I need to keep this URL structure. Please help.
Use MVC routing to make your URLs the same as your old site.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home",
url: "Home.aspx",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "About",
url: "About.aspx",
defaults: new { controller = "Home", action = "About" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note that in MVC 5 you could use attribute routing as an alternative to putting every route in the shared RegisterRoutes method.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Important: Put this before your default route
// or attribute routing won't work.
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
public class HomeController : Controller
{
[Route("Home.aspx", Name = "Home")]
public ActionResult Index()
{
return View();
}
[Route("About.aspx", Name = "About")]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
}
Another alternative would be just to use the new URL scheme and use the IIS rewrite module to configure 301 redirects from your old URL locations to your new ones so you don't lose any traffic and all of your old hyperlinks will still work.
I am using mvc4 framework and .net framwork 4.5. I need a url like this:
www.examples.com/name (note: 'name' will be change dynamically)
which routes to the same page.
I have tried like this but getting error
My action method is like this:
public ActionResult Userlist(string status)
{
return View();
}
Route Config
routes.MapRoute(
"user",
"{status}",
new { controller = "Home", action = "Userlist" }
);
How can I create a route syntax and redirect this to a controller?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Add this route config
routes.MapRoute(
name: "Default_Userlist",
url: "{status}",
defaults: new { controller = "Home", action = "Userlist" },
namespaces: new[] { "MyMvcProject.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyMvcProject.Controllers" }
);
}
Don't forget to replace the "MyMvcProject" with the name of your project.
Issue
This is a bad practice because the value of the status could easily cause conflicts with your action methods.
I have a controller named Registration and an action method in it as the following:
public JsonResult GetReqs(GridSettings gridSettings, int rt)
{
...//whatever
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
So I added a route and now my RouteConfig.cs is like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RegReq",
url: "{Registration}/{GetReqs}/{rt}",
defaults: new { controller = "Registration", action = "GetReqs", rt = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
However I can't access the rt parameter and the action method GetReqs isn't called(I set a breakpoint on it but nothing happened). Where is the mistake?
Edit: Link example I tried : ~/Registration/GetReqs/1
I think you need to remove the brackets in your first route:
routes.MapRoute(
name: "RegReq",
url: "Registration/GetReqs/{rt}",
defaults: new { controller = "Registration", action = "GetReqs",
rt = UrlParameter.Optional }
);
The default route has {controller} to tell MVC to use the string in that section of the url as the controller name. You know the controller, so you just need to match the specific string.