Simple ASP.NET MVC views without writing a controller

后端 未结 5 602
一整个雨季
一整个雨季 2021-01-04 10:50

We\'re building a site that will have very minimal code, it\'s mostly just going to be a bunch of static pages served up. I know over time that will change and we\'ll want

5条回答
  •  情书的邮戳
    2021-01-04 11:25

    You will have to write a route mapping for actual controller/actions and make sure the default has index as an action and the id is "catchall" and this will do it!

        public class MvcApplication : System.Web.HttpApplication {
            public static void RegisterRoutes(RouteCollection routes) {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = "catchall" } // Parameter defaults
                );
    
            }
    
            protected void Application_Start() {
                AreaRegistration.RegisterAllAreas();
    
                RegisterRoutes(RouteTable.Routes);
    
                ControllerBuilder.Current.SetControllerFactory(new CatchallControllerFactory());
    
            }
        }
    
    public class CatchallController : Controller
        {
    
            public string PageName { get; set; }
    
            //
            // GET: /Catchall/
    
            public ActionResult Index()
            {
                return View(PageName);
            }
    
        }
    
    public class CatchallControllerFactory : IControllerFactory {
            #region IControllerFactory Members
    
            public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) {
    
                if (requestContext.RouteData.Values["controller"].ToString() == "catchall") {
                    DefaultControllerFactory factory = new DefaultControllerFactory();
                    return factory.CreateController(requestContext, controllerName);
                }
                else {
                    CatchallController controller = new CatchallController();
                    controller.PageName = requestContext.RouteData.Values["action"].ToString();
                    return controller;
                }
    
            }
    
            public void ReleaseController(IController controller) {
                if (controller is IDisposable)
                    ((IDisposable)controller).Dispose();
            }
    
            #endregion
        }
    

提交回复
热议问题