ACTUALIZACIÓN: Esto ha sido publicado en codeplex. El código fuente completo, así como el ensamblado precompilado están disponibles para su descarga. No he tenido tiempo de publicar la documentación en el sitio todavía, por lo que esta publicación SO tendrá que ser suficiente por ahora.
ACTUALIZACIÓN: He añadido algunos nuevos atributos para manejar 1) de pedido ruta, 2) las limitaciones de los parámetros de ruta, y 3) valores por defecto parámetro de ruta. El texto a continuación refleja esta actualización.
De hecho, he hecho algo como esto para mis proyectos de MVC (no tengo idea de cómo Jeff lo está haciendo con stackoverflow). Definí un conjunto de atributos personalizados: UrlRoute, UrlRouteParameterConstraint, UrlRouteParameterDefault. Se pueden unir a los métodos de acción del controlador MVC para hacer que las rutas, restricciones y valores predeterminados se vinculen a ellos automáticamente. uso
Ejemplo:
(Nota este ejemplo es algo artificial pero demuestra la característica)
public class UsersController : Controller
{
// Simple path.
// Note you can have multiple UrlRoute attributes affixed to same method.
[UrlRoute(Path = "users")]
public ActionResult Index()
{
return View();
}
// Path with parameter plus constraint on parameter.
// You can have multiple constraints.
[UrlRoute(Path = "users/{userId}")]
[UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
public ActionResult UserProfile(int userId)
{
// ...code omitted
return View();
}
// Path with Order specified, to ensure it is added before the previous
// route. Without this, the "users/admin" URL may match the previous
// route before this route is even evaluated.
[UrlRoute(Path = "users/admin", Order = -10)]
public ActionResult AdminProfile()
{
// ...code omitted
return View();
}
// Path with multiple parameters and default value for the last
// parameter if its not specified.
[UrlRoute(Path = "users/{userId}/posts/{dateRange}")]
[UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
[UrlRouteParameterDefault(Name = "dateRange", Value = "all")]
public ActionResult UserPostsByTag(int userId, string dateRange)
{
// ...code omitted
return View();
}
Definición de UrlRouteAttribute:
/// <summary>
/// Assigns a URL route to an MVC Controller class method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteAttribute : Attribute
{
/// <summary>
/// Optional name of the route. If not specified, the route name will
/// be set to [controller name].[action name].
/// </summary>
public string Name { get; set; }
/// <summary>
/// Path of the URL route. This is relative to the root of the web site.
/// Do not append a "/" prefix. Specify empty string for the root page.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Optional order in which to add the route (default is 0). Routes
/// with lower order values will be added before those with higher.
/// Routes that have the same order value will be added in undefined
/// order with respect to each other.
/// </summary>
public int Order { get; set; }
}
Definición de UrlRouteParameterConstraintAttrib UTE:
/// <summary>
/// Assigns a constraint to a route parameter in a UrlRouteAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterConstraintAttribute : Attribute
{
/// <summary>
/// Name of the route parameter on which to apply the constraint.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Regular expression constraint to test on the route parameter value
/// in the URL.
/// </summary>
public string Regex { get; set; }
}
Definición de UrlRouteParameterDefaultAttribute:
/// <summary>
/// Assigns a default value to a route parameter in a UrlRouteAttribute
/// if not specified in the URL.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterDefaultAttribute : Attribute
{
/// <summary>
/// Name of the route parameter for which to supply the default value.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Default value to set on the route parameter if not specified in the URL.
/// </summary>
public object Value { get; set; }
}
Cambios en Global.asax.cs:
Reemplazar las llamadas a MapRoute, con una sola llamada a la RouteUtility. Función RegisterUrlRoutesFromAttributes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteUtility.RegisterUrlRoutesFromAttributes(routes);
}
Definición de RouteUtility.RegisterUrlRoutesFromAttributes:
La fuente completo está arriba en codeplex. Vaya al sitio si tiene comentarios o informes de errores.
Supongo que hacerlo con atributos impide el uso de rutas predeterminadas y restricciones de ruta ... –
Con este enfoque, nunca he necesitado rutas predeterminadas porque está vinculando cada ruta a un método específico. Tienes razón sobre las restricciones. Busqué la posibilidad de agregar restricciones como propiedad de atributo, pero me encontré con que las restricciones MVC se especifican utilizando objetos anónimos y las propiedades de los atributos solo pueden ser simples. Todavía es posible, creo que hacer restricciones como un atributo (con más codificación), pero no me he molestado todavía porque realmente no he necesitado restricciones en mi trabajo de MVC hasta este punto (tiendo a validar valores de ruta) en el controlador). – DSO
Me refiero a los valores predeterminados para los elementos en la ruta de la ruta como {nombre de usuario} pero también me doy cuenta de que suelen ser primitivos. –