【发布时间】:2012-01-19 08:39:49
【问题描述】:
我的问题是了解如何在页面没有要映射的控制器/视图时使用 uniq URL 呈现动态创建的页面。
我正在使用 Razor 在 ASP.NET MVC 3 3 中构建 CMS 系统。在数据库中,我存储页面/站点结构和内容。
我想我需要在控制器中进行一些渲染操作,以使用数据库中的内容创建自定义视图?那 URL 呢?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 razor
我的问题是了解如何在页面没有要映射的控制器/视图时使用 uniq URL 呈现动态创建的页面。
我正在使用 Razor 在 ASP.NET MVC 3 3 中构建 CMS 系统。在数据库中,我存储页面/站点结构和内容。
我想我需要在控制器中进行一些渲染操作,以使用数据库中的内容创建自定义视图?那 URL 呢?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 razor
我会创建一个单独的文件夹(如“DynamicContent”之类的)来保存这些动态页面,并在 Global.asax.cs 中为 RegisterRoutes 方法添加相应的IgnoreRoute 调用,如下所示:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("DynamicContent/{*pathInfo}");
...
}
之后,用户将能够使用类似的 URL 访问这些页面
http://%your_site%/DynamicContent/%path_to_specific_file%
更新
如果您不想在服务器硬盘上放置文件,那么您可以为这些文件创建一个特殊的控制器。这条路线应该是这样的:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"DynamicRoute", // Route name
"Dynamic/{*pathInfo}", // URL with parameters
new { controller = "Dynamic", action = "Index"} // Parameter defaults
);
}
您的 DynamicController.cs 应如下所示:
public class DynamicController : Controller
{
public ActionResult Index(string pathInfo)
{
// use pathInfo value to get content from DB
...
// then
return new ContentResult { Content = "%HTML/JS/Anything content from database as string here%", ContentType = "%Content type either from database or inferred from file extension%"}
// or (for images, document files etc.)
return new FileContentResult(%file content from DB as byte[]%, "%filename to show to client user%");
}
}
请注意,pathInfo 之前的星号 (*) 将使此路由获取 Dynamic 之后的整个 URL 部分 - 因此,如果您输入了 http://%your_site%/Dynamic/path/to/file/something.html,那么整个字符串 path/to/file/something.html 将在参数 pathInfo 中传递给 DynamicController/索引方法。
【讨论】: