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!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…