Base controller for ASP.NET MVC

Is there a way to create an implementation of a base controller that handles all routes?

IE / home / index and / about / index point to one controller method and return a view.

The site I create is 90% static content, and I don’t want to go and create 50 controllers.

Need to be alright?

+3
source share
4 answers

Remember that “controller” and “action” are keywords for a routing system for its dynamic magic. If you simply replace the “controller” parameter on your route with some other parameter name, you can always use the default controller.

routes.MapRoute("Default",
                "{whatever}/{action}/{id}",
                new { controller="Home", action="Index", whatever="", id="0" } );

, "".

+1

, , , , - . , - :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return RedirectToAction("Index", new { controller = "Main" });
    }
}

public class AboutController : Controller
{
    public ActionResult Index()
    {
        return RedirectToAction("Index", new { controller = "Main" });
    }
}

public class MainController : Controller
{
    public ActionResult Index()
    {
        // Do something important.
        // Do something else important.
        return View();
    }
}

AboutController, HomeController AboutController. , , , , - . , .

+1

ya with the correct routing in the global.asax file, you can do this. But it will be difficult for you to manage the site after a while for refactoring or for any reason. Here you will learn about routing in asp.net mvc: http://www.asp.net/learn/mvc/#MVC_Routing

0
source

Since you are not going to map controllers or methods based on the URL, you just need to commit several parameters and then do something with them.

 routes.MapRoute( 
     "MyNewRoute", 
     "{firstParameter}/{secondParameter}",
     new {controller="Home", action="Index"} 
 ); 

 public ActionResult Index(string firstParameter, string SecondParameter)
 {
     if (firstParameter == "Home")
     {
        // Do something
     }
 }
0
source

Source: https://habr.com/ru/post/1729185/


All Articles