Set default controller in MVC4 - c#

How to set the default controller in MVC4?
I've tried adding the below code to the Global.ascx but it said "Only assignment, call, increment, decrement, and new object expressions can be used as a statement", seems it can't find the "route", did I put it on the wrong place?
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
Below is the screenshot:

Take a look at App_Start/RouteConfig.cs file. This is where you will be able to configure routes in the way you want.
There, you will find code similar to this:
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 }
);
}
}

you need to put this code inside RouteConfig.cs under App_Start.
check ASP.NET MVC 4: Where Have All The Global.asax Routes Gone?

The answers suggesting to use RouteConfig are correct but a bit misleading. There's nothing magical about RouteConfig; it's just a class that you create, name, and locate according to convention.
The important part is what you typically pass to RouteConfig: RouteTable.Routes
The route table is available from anywhere within an ASP.Net application. For example, you could say:
protected void Application_Start()
{
RouteTable.Routes.MapRoute( "myroute", "apples", new { controller = "Foo", action = "Bar" } );
}
and it would work just fine. Of course, you should only initialize routes on startup and follow the convention of RouteConfig for consistency.
But it's worth knowing why it works.

Please change it in your RouteConfig.cs file

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");
}

How can I do route configuration in ASP.NET MVC?

How can I do route configuration as below?
My current url is: http://localhost:4815/Home/ByCategory/1
But I want it to be: http://localhost:4815/CategoryTitle
public ActionResult ByCategory(int? id)
{
...
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "ByCategory", id = UrlParameter.Optional }
);
You can use Attribute Routing. for doing this at first you must Enable it by
adding below code top of your MapRoute in RouteConfig:
routes.MapMvcAttributeRoutes(); //Enables Attribute Routing
then you can add Attribute Routing at top of your classes and methods:
[Route("CategoryTitle")]
public ActionResult ByCategory(int? id)
{
...
}
for deep dive in Routing, you can follow this link.
good luck.
If you want to parametrize a route with Category Title, you can use Attribute Routing like so
[Route("~/{categoryTitle}")]
public ActionResult ByCategory(string categoryTitle)
...
Thank you for your suggestions. I have added the following code to routeconfig. I used on the view page to go to the relevant controller
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "AddQuestion",
url: "AddQuestion",
defaults: new { controller = "Question", action = "Create" }
);

ASP.NET MVC 4 Parameters Separated by Forward Slashes "/" not passing args properly

I am trying to follow a convention used by many sites that pass in arguments with multiple forward slashes, as opposed to using the GET model.
That is, I am looking to consume a URL like:
http://www.foo.bar/controller/action?arg1=a&arg2=b&arg3=c
In this fashion:
http://www.foo.bar/controller/action/a/b/c
I currently have this (mostly) working, using the following:
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: "Sandbox",
url: "Sandbox/{action}/{*args}",
defaults: new { controller = "Sandbox", action = "Index", args = UrlParameter.Optional }
);
}
However, if I pass in something like
http://www.foo.bar/Sandbox/Index/a
or
http://www.foo.bar/Sandbox/Index/a/
The Controller and action are appropriately called:
public ActionResult Index(string args)
{
return View();
}
but args is null.
However, if I pass in something like:
http://www.foo.bar.com/Sandbox/Index/a/b
Then args is "a/b", as desired.
I have been scouring SO and the rest of the web, but can't seem to find the solution.
Is there something obvious I am missing to correct this behavior?
Am I looking for the wrong terminology?
Note: I was able to repro this issue with a brand new ASP.NET application using Windows Authentication. All that was done:
Create ASP.NET application in VS 2015
Choose MVC
Click on Change Authentication
Select Windows Authentication
Add the above Map Route to RouteConfig.cs
Create SandboxController.cs and add the args parameter to Index
Create the Index.cshtml view
Repro the problem using http://localhost:55383/Sandbox/Index/a
Repro the expected behavior using http://localhost:55383/Sandbox/Index/a/b
Any help is very appreciated. Thank you!
Similar question, but doesn't help me: URLs with slash in parameter?
Never mind... Here is the problem...
The MapRoute is calling the default route, first.
To fix it, I just swapped the Default map route with the Sandbox route.
I hope this helps someone.
Working Solution:
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Sandbox",
url: "Sandbox/{action}/{*args}",
defaults: new { controller = "Sandbox", action = "Index", args = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

How to use shortened url with asp.net mvc routing?

I'd like to understand how to set routing parameters to do the follow: when user call shortened url like http://hostname.com/shortenedurl my asp.net mvc project should call action and parameter like http://hostname.com/controller/action
Never before I did something like that so I will be appreciate for any advise. How code and decode url string from normal to short and back I know already.
You can define specific routes in RouteConfig.cs file. For example, .../MyShortUrl will route to the Edit method of EmployeeController
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MyShortUrl",
url: "MyShortUrl",
defaults: new { controller = "Employee", action = "Edit", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Note specific routes need to placed in order before more general routes
There is no "normal" and "short". It would be best if you used Routing. It's important to read some introduction to Routing to understand how it works.
(I don't think an extract would be appropriate here since the whole article needs to be read and its concepts understood.)

How to specify route options to specific controllers in ASP.NET MVC 5

I would like to suppress the controller from the route, and it worked fine using this:
routes.MapRoute(
name: "HomePages",
url: "{action}",
defaults: new { controller = "Home", action = "Index" }
);
The problem is when doing the same for a different controller like "Account", the first option only will take effect :
routes.MapRoute(
name: "LoginRoute",
url: "{action}",
defaults: new { controller = "Account", action = "Login" }
);
My objective is to hide the controller from the route, so i can directly access mysite.com/login and mysite.com/index, how to achieve that when login is under Account controller and index is under Home controller?
How to specify the second option for the Account actions, and keep the first for the Home actions?
Have you thought about using the Routing attributes e.g:
[Route("{getId:int}")]
public ActionResult Show(int getId) { ... }
you can use this in conjunction with the old way of routing. You do need to explicitly set this functionality in your config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
I have found the routing Attributes makes it very easy to set good routes on my controller methods. This also bleeds into web api and RESTFul stuff as well.

Categories