Database selection before routing in ASP.Net MVC

后端 未结 1 591
野趣味
野趣味 2020-12-18 17:12

I\'m looking for a way in asp.net mvc 4, to select database settings from web.config before any routing takes place, like pre routing hooks in codeigniter(php). What is the

相关标签:
1条回答
  • 2020-12-18 17:36

    Are you asking for getting values from Web.Config or from Database? It's a bit confusing tbh, but here is some code that will do both.

    You can create your own Route Handler, and here you can do what ever you want pretty much. Then in the RouteConfig.cs, make sure to use your own Route Handler.

    This is MyRouteHander.cs

    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace My.Services
    {
        public class MyRouteHander : IRouteHandler
        {
             ApplicationDbContext Db = new ApplicationDbContext();
             public IHttpHandler GetHttpHandler(RequestContext requestContext)
             {
    
                 // Get route data values
                 var routeData = requestContext.RouteData;
                 var action = routeData.GetRequiredString("action");
                 var controller = routeData.GetRequiredString("controller");
    
                 // Get webconfig settings
                 var webConfigSetting = ConfigurationManager.AppSettings["SOME_FANCY_SETTING"]
                 if (!string.IsNullOrEmpty(webConfigSetting))
                 {
                    requestContext.RouteData.Values["action"] = webConfigSetting;
                    return new MvcHandler(requestContext);
                 }
    
                 // If we have SomeDataBaseTable hit we do something else.
                 if (Db.SomeDataBaseTable.Any(x => x.Action == action))
                 {
                     // Lets do something with the requestContext.
                     string actionName = "SpecialAction";
                     requestContext.RouteData.Values["action"] = actionName;
                     requestContext.RouteData.Values["controller"] = "SpecialController";
                     requestContext.RouteData.Values.Add("id", Db.SomeDataBaseTable.FirstOrDefault(x => x.Action == action).Id);
                 }
                 return new MvcHandler(requestContext);
             }
         }
     }
    

    App_Start/RouteConfig.cs update the routes.MapRoute() so it uses your MyRouteHander.

    routes.MapRoute(
          "Home",
          "Home/{action}/{id}",
          new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "MyProject.Controllers" }
        ).RouteHandler = new MyRouteHander();
    
        routes.MapRoute(
          "Default",
          "{controller}/{action}/{id}",
          new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "MyProject.Controllers" }
        ).RouteHandler = new MyRouteHander();
    ...
    

    Hope this helps!

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