Setting up a simple ASP.NET MVC route - c#

I am working with ASP.NET MVC 4 and am attempting to write a really basic route, but it's not working and getting very frustrated with it!
I want the URL http://www.mywebsite.com/my-page to trigger the controller called Page and the action method Index.
I have no other route setup apart from this:
RouteTable.Routes.MapRoute(
name: "Default",
url: "my-page",
defaults: new { controller = "Page", action = "Index" }
);
Is there something incorrect with my setup or where am I going wrong?
The error I get is:
The controller for path '/my-page' was not found or does not implement IController.

Main problem is you are trying to override the default route. In MVC4, the routes are defined in App_Start/RouteConfig.cs. The "Default" route should be the LAST route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Then, for your specific route, use the following BEFORE the default route:
routes.MapRoute(
name: "MyPage",
url: "my-page",
defaults: new { controller = "Page", action = "Index" }
);
Fianlly, ensure you have a controller PageController.cs with an action Index and a View Views/Page/Index.cshtml:
public class PageController : Controller
{
public ActionResult Index()
{
return View();
}
}

Related

Is it possible to host Asp.net MVC web App locally [duplicate]

In asp.net MVC the "homepage" (ie the route that displays when hitting www.foo.com) is set to Home/Index .
Where is this value stored?
How can I change the "homepage"?
Is there anything more elegant than using RedirectToRoute() in the Index action of the home controller?
I tried grepping for Home/Index in my project and couldn't find a reference, nor could I see anything in IIS (6). I looked at the default.aspx page in the root, but that didn't seem to do anything relevent.
Thanks
Look at the Default.aspx/Default.aspx.cs and the Global.asax.cs
You can set up a default route:
routes.MapRoute(
"Default", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.
ASP.NET Core
Routing is configured in the Configure method of the Startup class. To set the "homepage" simply add the following. This will cause users to be routed to the controller and action defined in the MapRoute method when/if they navigate to your site’s base URL, i.e., yoursite.com will route users to yoursite.com/foo/index:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=FooController}/{action=Index}/{id?}");
});
Pre-ASP.NET Core
Use the RegisterRoutes method located in either App_Start/RouteConfig.cs (MVC 3 and 4) or Global.asax.cs (MVC 1 and 2) as shown below. This will cause users to be routed to the controller and action defined in the MapRoute method if they navigate to your site’s base URL, i.e., yoursite.com will route the user to yoursite.com/foo/index:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional }
);
}
Step 1: Click on Global.asax File in your Solution.
Step 2: Then Go to Definition of
RouteConfig.RegisterRoutes(RouteTable.Routes);
Step 3: Change Controller Name and View Name
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 }
);
}
}
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 = "Your Controller", action = "Your Action", id = UrlParameter.Optional }
);
}
}
Attribute Routing in MVC 5
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
check RegisterRoutes method in global.asax.cs - it's the default place for route configuration...
I tried the answer but it didn't worked for me. This is what i ended up doing:
Create a new controller DefaultController. In index action, i wrote one line redirect:
return Redirect("~/Default.aspx")
In RouteConfig.cs, change controller="Default" for the route.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
If you don't want to change the router, just go to the HomeController
and change MyNewViewHere in the index like this:
public ActionResult Index()
{
return View("MyNewViewHere");
}

Returning a 404 when the URL does not contain Index

I am having trouble with routing in MVC. I have created a controller for my contact page, but unless I specify the route as /contact/index it will return a 404. I cannot see why it can't find the View with just /contact in the URL. My RouteConfig looks fine to me.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "T",
url: "T/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The only reason I can see it not finding its View is because of the new Route I have configured to display a site holding page. Interestingly /t does display the 'demo' homepage, so I can't see why it doesn't like just /contact.
This S.O article told me that I could fix the problem by giving it its own MapRoute but I shouldn't have to do all that?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Holding()
{
return View();
}
}
public class ContactController : Controller
{
// GET: Contact
public ActionResult Index()
{
return View();
}
}
It must be something silly, but I can't work it out.
You have route conflicts
/contact would match
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
But since contact controller has no Holding action you will get a 404 Not Found
And since it matched the Holding route it wont go on to the next Default route as first match wins.
The added route is too general so it will get a lot of false matches.
Based on the controllers shown, the added route is not needed. the holding path would still match the default route template. So it can actually be removed altogether.

MVC Uri Parameter is null

When attempting to pass a parameter to a simple controller I receive the parameter as always being null.
Controller
public class GetOrgController : Controller
{
private DirectoryEntities de;
public getOrgController()
{
de = new DirectoryEntities();
}
// GET: getOrg
public ActionResult Index(string district)
{
getorg_Result org = de.getorg(district).FirstOrDefault();
return View(org);
}
}
When I try to navigate to that url with a parameter localhost:660366/GetOrg/Index/D123 the district variable is always null.
I thought maybe it had to do something with the default RouteConfig. When I put a new value ahead of the default route config it worked! However now, whenever I try to launch the application it goes to the GetOrgController first. What happens when I want a new controller with different parameters? I have to do this every time? Here is my new RouteConfig with the new entry.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "GetOrg",
url: "{controller}/{action}/{district}",
defaults: new { controller = "GetOrg", action = "Index", district = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I actually started doing Rest initially in Web Api 2, but the view-model attracted me to MVC. It is a lot easier specifiying above the method the routes/parameters I wanted like below. Is this possible in MVC?
WebApi2
[Route("Index/{district}")]
public ActionResult Index(string district)
{
getorg_Result orgs = de.getorg(district).FirstOrDefault();
return View(orgs);
}
The above method seems so much cleaner than having to rely on the order of controllers being correct in the RouteConfig
These two routes literally make no sense. The first one says, for ANY controller with ANY method default to GetOrgController. That isn't what you want because now id won't work for all the other controllers and the second MapRoute is close to a duplicate.
routes.MapRoute(
name: "GetOrg",
url: "{controller}/{action}/{district}",
defaults: new { controller = "GetOrg", action = "Index", district = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What you really should be doing is saying for any call starting with GetOrg then call GetOrgController for any method....
routes.MapRoute(
name: "GetOrg",
url: "GetOrg/{action}/{district}",
defaults: new { controller = "GetOrg", action = "Index", district = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
thats because both routs are generic thats why it hits the first route by default so you can remove UrlParameter.Optional so that the route should be a little specific
routes.MapRoute(
name: "GetOrg",
url: "{controller}/{action}/{district}",
defaults: new { controller = "GetOrg", action = "Index"}
);
but still you can use the default route for that purpose no need of additional route unless you want to use a custom url like random/234

Since I wrote a route for a specific Action of a Controller, do I need to write a route for all Actions inside the Controller?

I'm writing few routes for my MVC application. I have the following routes for my application:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
The route above is used when I want to access default values like:
www.servicili.com/budget/edit/1
www.servicili.com/professional/view/234
But, I create the following route for a specific purpose:
routes.MapRoute(
name: "Perfil",
url: "{UsuApelido}",
defaults: new { controller = "Perfil", action = "Index"}
);
the route above, is used to access the URL profile of a "plumber" for example:
www.servicili.com/MarkZuckberg
the profile details are on the controller Perfil and Action Index, however, since I wrote this route, all other actions aren't working.
For example: If I try to access the Index action inside another controller, it redirect to Index of Perfil.
--
The question is: Since I wrote a route for a specific Action of a Controller, do I need to write a route for all Actions inside the Controller?
To solve your problem try like this,
First define constraint,
public class PlumberUrlConstraint: IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var db = new YourDbContext();
if (values[parameterName] != null)
{
var UsuApelido = values[parameterName].ToString();
return db.Plumbers.Any(p => p.Name == UsuApelido);
}
return false;
}
}
Define two routes, put "Default" route at 2nd position
routes.MapRoute(
name: "Perfil",
url: "{*UsuApelido}",
defaults: new { controller = "Perfil", action = "Index"},
constraints: new { UsuApelido = new PlumberUrlConstraint() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Pages", action = "Index", id = UrlParameter.Optional }
);
Now if you have an 'Index' action in 'Perfil' Controller, you can get plumber name like this,
public ActionResult Index(string UsuApelido)
{
//load the content from db with UsuApelido
//display the content with view
}
Hope this help.

MVC 5 Routing Issue - Mutiple Routes Incorrectly Targeting Same View

I have multiple routes configured, but for some reason, despite the rules addressing different Controllers and different Views, different links are routing to the same view. Please see below, I have included my RouteConfig file and example links below:
RouteConfig.cs
using System.Web.Mvc;
using System.Web.Routing;
namespace WebApplication1
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Account",
url: "Account/{action}/{id}",
defaults: new { controller = "Account", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Member",
url: "Member/{action}/{id}",
defaults: new { controller = "Member", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Root",
url: "{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Details",
url: "{controller}/{action}/{u}",
defaults: new
{
controller = "Member",
action = "Details",
u = UrlParameter.Optional
}
);
routes.MapRoute(
name: "Article",
url: "{Home}/{Article}/{id}/{articleName}",
defaults: new { controller = "Home", action = "Article" }
);
routes.MapRoute(
name: "Item",
url: "{News}/{Item}/{id}/{itemName}",
defaults: new { controller = "News", action = "Item" }
);
}
}
}
Links
http://localhost:11508/Home/Article/2/Participate
http://localhost:11508/News/Item/2/Second-Test
As so can see, the links and rules are most certainly unique but for some reason the Item rule is being ignored, it is simply passing Id 2 to the Home/Article view.
You shouldn't include controller / action names in brackets - just pass them as is, so that path can be matched. Your last two routes should look like this:
routes.MapRoute(
name: "Article",
url: "Home/Article/{id}/{articleName}",
defaults: new { controller = "Home", action = "Article" }
);
routes.MapRoute(
name: "Item",
url: "News/Item/{id}/{itemName}",
defaults: new { controller = "News", action = "Item" }
);
Also, it is good to place such specific routes before any other routes, not after default routes.
UPDATE
Basically it should be separate question, but it is easier to just answer it here.
From comment:
how I can get http://localhost:11508/Member/Details?u=testuser to be routed to http://localhost:11508/Member/Details/testuser instead of a showing parameter.
Create controller action which accepts this parameter, like this one:
public ActionResult Details(string u, ...)
{
var model = new ...
...
return View(model);
}
Register route, which accepts u parameter as URL part, like this one
routes.MapRoute(
name: "MyRoute",
url: "Member/Details/{u}",
defaults: new { controller = "Member", action = "Details", u = UrlParameter.Optional }
);
Here {u} actually declares parameter name, and how it should be used (parsed / rendered) inside URL.
Render link to the URL like this one:
linktext
In all these steps, u is that name of parameter which you will use.
The Mapping takes the first matching rule.
The "Item"-Route would never be used because the Article-Root will catch all request that could match "Item"-Route.
Check the order of the routes AND delete the {} surrounding news.
routes.MapRoute(
name: "Item",
url: "News/Item/{id}/{itemName}",
defaults: new { controller = "News", action = "Item" }
);
Your problem is in the order in which you are registering your routes. The rule is that you should register them from the most specific to the least. In other words, your "default" route(s) should be the very last.
With how you have it right now, MVC gets a hit on your default route, because your item route matches that, so once it hits on that, it stops looking for other routes and uses it.
Move your item route up to the top of your RegisterRoutes method and it should work fine.

Categories