ASP.NET MVC Custom route regex to catch a substring of elements and check for their existence

I am trying to create my own route for a URL with the following format:

http: // domain / nodes / {item_1} / {item_2} / {item3 _} /..../ {item_ [n]}

In principle, there may be a random amount of item_ [n], for example

http://domain/nodes/1/3/2 

http://domain/nodes/1

http://domain/nodes/1/25/11/45

Using my custom route, I would like to get an array of elements and execute some logic (check and add some specific information to request a context) with them.

For example, from [http: // domain / nodes / 1/25/11/45] I would like to get an array from [1, 25, 11, 45] and process it.

So, I have 2 problems.

The first question is actually. Am I looking in the right direction? Or could there be an easier way to accomplish this (possibly without custom routes)?

URL . - ?

:)

+3
2

, , , params accordinlgy.

  public class CustomRouting : RouteBase
  {
     public override RouteData GetRouteData(HttpContextBase httpContext)
     {
       RouteData result = null;
       var repository = new FakeRouteDB(); //Use you preferred DI injector
       string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath;
       string[] sections = requestUrl.Split('/');
       /*
       from here you work on the array you just created
       you can check every single part
       */
       if (sections.Count() == 2 && sections[1] == "")
         return null; // ~/

       if (sections.Count() > 2) //2 is just an example
       {
         result = new RouteData(this, new MvcRouteHandler());
         result.Values.Add("controller", "Products");
         result.Values.Add("action", "Edit");
         result.Values.Add("itmes0", sections[1]);
         if (sections.Count() >= 3)
         result.Values.Add("item2", sections[2]);
         //....
       }
       else
       {
         //I can prepare a default route        
         result = new RouteData(this, new MvcRouteHandler());
         result.Values.Add("controller", "Home");
         result.Values.Add("action", "Index");
       }
       return result;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
     //I just work with outbound so it ok here to do nothing
     return null;
    }
}

global.asax

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.Add(new CustomRouting());

  routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

, . , .

+1

, .

- ? , .

:

@"http://domain/nodes(?:/(\d+))*"

(?:) - , () - .
, 1-n, ( 0 ).

0

All Articles