tag route parameter page net mvc form data asp all asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing

asp.net - route - href controller asp net mvc



Infinite URL Parameters para la ruta ASP.NET MVC (4)

Necesito una implementación en la que pueda obtener infinitos parámetros en mi controlador ASP.NET. Será mejor si te doy un ejemplo:

Supongamos que tendré las siguientes URL:

example.com/tag/poo/bar/poobar example.com/tag/poo/bar/poobar/poo2/poo4 example.com/tag/poo/bar/poobar/poo89

Como puede ver, obtendrá infinitas etiquetas después de example.com/tag/ y barra será un delimitador aquí.

En el controlador, me gustaría hacer esto:

foreach(string item in paramaters) { //this is one of the url paramaters string poo = item; }

¿Hay alguna forma conocida de lograr esto? ¿Cómo puedo llegar a los valores del controlador? Con Dictionary<string, string> o List<string> ?

NOTA :

La pregunta no está bien explicada por la OMI, pero hice todo lo posible para encajarla. pulg. Siéntase libre de modificarlo


El catch all te dará la cadena en bruto. Si desea una forma más elegante de manejar los datos, siempre puede usar un manejador de ruta personalizado.

public class AllPathRouteHandler : MvcRouteHandler { private readonly string key; public AllPathRouteHandler(string key) { this.key = key; } protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var allPaths = requestContext.RouteData.Values[key] as string; if (!string.IsNullOrEmpty(allPaths)) { requestContext.RouteData.Values[key] = allPaths.Split(''/''); } return base.GetHttpHandler(requestContext); } }

Registra el manejador de ruta.

routes.Add(new Route("tag/{*tags}", new RouteValueDictionary( new { controller = "Tag", action = "Index", }), new AllPathRouteHandler("tags")));

Obtenga las etiquetas como una matriz en el controlador.

public ActionResult Index(string[] tags) { // do something with tags return View(); }


En caso de que alguien venga a esto con MVC en .NET 4.0, debe tener cuidado donde define sus rutas. Estaba feliz de ir a global.asax y agregar rutas como se sugiere en estas respuestas (y en otros tutoriales) y llegar a ninguna parte. Mis rutas solo se han predeterminado en {controller}/{action}/{id} . Agregar más segmentos a la URL me dio un error 404. Luego descubrí el archivo RouteConfig.cs en la carpeta App_Start. Resulta que este archivo es llamado por global.asax en el método Application_Start() . Por lo tanto, en .NET 4.0, asegúrese de agregar allí sus rutas personalizadas. Este artículo lo cubre maravillosamente.



Me gusta esto:

routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... }); ActionResult MyAction(string tags) { foreach(string tag in tags.Split("/")) { ... } }