Tor*_*Guy 80 asp.net-mvc routing url-routing decorator
在StackOverflow播客#54中,Jeff提到他们通过处理路由的方法上方的属性在StackOverflow代码库中注册其URL路由.听起来像一个很好的概念(菲尔哈克提出的关于路线优先事项的警告).
有人可以提供一些样本来实现这一目标吗?
此外,使用这种路由风格的任何"最佳实践"?
DSO*_*DSO 62
更新:这已发布在 codeplex上.完整的源代码以及预编译的程序集可供下载.我还没有时间在网站上发布文档,所以这篇SO帖子现在已经足够了.
更新:我添加了一些新属性来处理1)路由排序,2)路由参数约束,以及3)路由参数默认值.以下文字反映了此更新.
我实际上已经为我的MVC项目做了类似的事情(我不知道Jeff是如何使用stackoverflow做的).我定义了一组自定义属性:UrlRoute,UrlRouteParameterConstraint,UrlRouteParameterDefault.它们可以附加到MVC控制器操作方法,以使路由,约束和默认值自动绑定到它们.
用法示例:
(注意这个例子有点做作,但它演示了这个特性)
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();
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
UrlRouteParameterConstraintAttribute的定义:
/// <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; }
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
对Global.asax.cs的更改:
将调用替换为MapRoute,只需调用RouteUtility.RegisterUrlRoutesFromAttributes函数:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteUtility.RegisterUrlRoutesFromAttributes(routes);
}
Run Code Online (Sandbox Code Playgroud)
RouteUtility.RegisterUrlRoutesFromAttributes的定义:
完整的源代码在codeplex上.如果您有任何反馈或错误报告,请访问该网站.
spo*_*pot 44
您也可以尝试AttributeRouting,它可以从github上或通过的NuGet.
这是一个无耻的插件,因为我是项目作者.但是,如果我不是很高兴使用它.你可能也是.github存储库wiki中有大量文档和示例代码.
有了这个库,你可以做很多事情:
我确定还有其他一些我忘了的东西.看看这个.通过nuget安装很轻松.
注意:截至4/16/12,AttributeRouting还支持新的Web API基础结构.以防你正在寻找可以处理的东西.谢谢subkamran!
1.下载RiaLibrary.Web.dll并在ASP.NET MVC网站项目中引用它
2.使用[Url]属性解压缩控制器方法:
public SiteController : Controller
{
[Url("")]
public ActionResult Home()
{
return View();
}
[Url("about")]
public ActionResult AboutUs()
{
return View();
}
[Url("store/{?category}")]
public ActionResult Products(string category = null)
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,'?' 登录'{?category}'参数意味着它是可选的.您不需要在路由默认值中明确指定它,这等于:
routes.MapRoute("Store", "store/{category}",
new { controller = "Store", action = "Home", category = UrlParameter.Optional });
Run Code Online (Sandbox Code Playgroud)
3.更新Global.asax.cs文件
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoutes(); // This does the trick
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
Run Code Online (Sandbox Code Playgroud)
如何设置默认值和约束?例:
public SiteController : Controller
{
[Url("admin/articles/edit/{id}", Constraints = @"id=\d+")]
public ActionResult ArticlesEdit(int id)
{
return View();
}
[Url("articles/{category}/{date}_{title}", Constraints =
"date=(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])")]
public ActionResult Article(string category, DateTime date, string title)
{
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
如何订购?例:
[Url("forums/{?category}", Order = 2)]
public ActionResult Threads(string category)
{
return View();
}
[Url("forums/new", Order = 1)]
public ActionResult NewThread()
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24647 次 |
| 最近记录: |