开发者

How can I call ASP.Net MVC based on urls checked against a lookup table?

开发者 https://www.devze.com 2023-01-19 03:12 出处:网络
I\'ve got a unique requirement in my unique ASP.Net MVC project. Basically we are migrating an older Linux based website to MVC and we want to preserve the URLs which were on the last website.

I've got a unique requirement in my unique ASP.Net MVC project. Basically we are migrating an older Linux based website to MVC and we want to preserve the URLs which were on the last website.

It is not practical to create开发者_高级运维 a new controller for the subdirectory (ex. 'www.mywebsite.com/pickes/cherry-pickle-recipe.html') of the website.

So I want to do one of the following

  1. Create a lookup list for the URLs. The URLs should be checked against a database and if a URL is found certain action should be returned from a certain controller.

  2. Trap all url requests which didn't have a controller and send them to a certain controller-> action.

How should I go about this?


Well I think you can do this by writing a custom routehandler by implementing IRouteHandlerInterface

public class LookupRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        IRouteHandler handler = new MvcRouteHandler();
        var vals = requestContext.RouteData.Values;
        if(String.IsNullOrEmpty(vals["controller"])
        {
           // fetch action and controller from database
           vals["controller"] = dbcontroller;
           vals["action"] = dbaction;
        } 
        return handler.GetHttpHandler(requestContext);
    }
}

You have to do one more thing i.e register your route handler in global.asax like

routes.MapRoute(
   "dbroute",
   "{controller}/{action}/{id}",
   new {  id = "" }
   ).RouteHandler = new LookupRouteHandler();
0

精彩评论

暂无评论...
验证码 换一张
取 消