Url routing with database lookup?

后端 未结 4 671
孤街浪徒
孤街浪徒 2021-01-06 12:25

I want to build a ASP.NET MVC site so that the controller for a specific url is stored in the database instead of the URL.

The reason for that is that i\'m building

相关标签:
4条回答
  • 2021-01-06 13:13

    Why couldn't you just do something like this:

    -- Global.asax.cs --

     routes.MapRoute(null,              // Route name
                     "content/{id}",    // URL with parameters               
                     new { Controller = "Content", Action = "Show", Id = (string) null });  // Parameter defaults
    

    -- /Controllers/ContentController.cs --

    public class ContentController : Controller
    {
        public ActionResult Show(string id)
        {
            // Lookup the 'content' (article, page, blog post, etc) in the repository (database, xml file, etc)
            ContentRepository repository = new ContentRepository();
            Content content = repository.FindContent(id);
            return View(content);
        }
    }
    

    Such that a request to your site www.yoursite.com/content/welcome-to-my-first-blog-post would call ContentController.Show("welcome-to-my-first-blog-post").

    0 讨论(0)
  • 2021-01-06 13:17

    "for a system with like 100,000 pages it feels like a bad idea."

    It is a bad idea if you are creating a routing system that cannot be reused. The basic {controller}/{action}/{id} schema points you in the direction of reuse. This schema can be extended/revamped/recreated according to your needs.

    Instead of thinking about how many pages you have think about how your resources can be grouped.

    Instead of creating a heavy routing system why not create an anchor link control (ascx) which allows user to only add valid internal links. Keep a table in the db of your templates and their controllers to populate the control with it.

    0 讨论(0)
  • 2021-01-06 13:24

    I suppose ASP.NET can do many of the same things as PHP. If so there is a simple approach.

    With rewrite rules you can easily send any traffic to any URL of the 100K to the same place. On that destination you could simply use the server variables containing the URL requested by the client and extract the location. Look it up in the DB and send the corresponding data for that URL back to the client on-the-fly.

    0 讨论(0)
  • 2021-01-06 13:26

    Basically you'll have to implement your own IRouteHandler.

    Part of the answer and some example code is in Option 3 of this question's answer: ASP.NET MVC custom routing for search

    More information: http://weblogs.asp.net/fredriknormen/archive/2007/11/18/asp-net-mvc-framework-create-your-own-iroutehandler.aspx

    0 讨论(0)
提交回复
热议问题