asp.net mvc项目中实现伪静态
前沿
asp.net mvc开发的网站,为了对SEO优化友好,且为了页面的URL地址看起来更好看些,就首先尝试了一下伪静态的实现,在此记录,以备忘~~
下载安装插件
在asp.net mvc中实现伪静态化,需要借助UrlRewrite.dll库,所以首先要使用nuget下载安装,如下图所示:
安装完成后,会自动在webconfig中添加如下的配置信息:
WebConfig配置
然后我们需要手动添加一些配置信息,如下图:
相应的代码如下:
<section name="CustomConfiguration" type="URLRewriter.Config.UrlsSection, URLRewriter" />
<CustomConfiguration>
<urls>
<!--([\w]+)表示,1到n个字母或数字或下划线或汉字组成-->
<add virtualUrl="~/Index.html" destinationUrl="~/Home/Index" />
<add virtualUrl="~/(\d+)/Detail.html" destinationUrl="~/Home/Detail/?guid=$1" />
</urls>
</CustomConfiguration>
<urls>
<!--([\w]+)表示,1到n个字母或数字或下划线或汉字组成-->
<add virtualUrl="~/Index.html" destinationUrl="~/Home/Index" />
<add virtualUrl="~/(\d+)/Detail.html" destinationUrl="~/Home/Detail/?guid=$1" />
</urls>
</CustomConfiguration>
路由配置
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( // 不带参数的伪静态路由
name: "Index.html",
url: "{controller}/{action}.html",
defaults: new { controller = "Home", action = "Index" },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute(
"IDHtml", // 只有一个参数id的伪静态路由
"{controller}/{action}/{id}.html",// 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute(//两个参数(id和pid)不带动作,伪静态
"TwoparameterNoAction",
"{controller}/{action}/{id}/{pid}.html",
new { controller = @"[a-zA-Z]", action = "Index", id = @"[\d]{0,6}", pid = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute( // 默认路由配置
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
}
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( // 不带参数的伪静态路由
name: "Index.html",
url: "{controller}/{action}.html",
defaults: new { controller = "Home", action = "Index" },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute(
"IDHtml", // 只有一个参数id的伪静态路由
"{controller}/{action}/{id}.html",// 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute(//两个参数(id和pid)不带动作,伪静态
"TwoparameterNoAction",
"{controller}/{action}/{id}/{pid}.html",
new { controller = @"[a-zA-Z]", action = "Index", id = @"[\d]{0,6}", pid = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
routes.MapRoute( // 默认路由配置
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Site.WebApp.Controllers" }
);
}