珂珂的个人博客 - 一个程序猿的个人网站

FYJ.Blogs开发系列(八)-自定义路由

    实现伪静态有很多种方法,不过我发现asp.net mvc的路由也可以实现

这里有个问题倒是纠结了很久,就是需要注释掉RouteConfig.cs中默认的路由或者移动都最后

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Blog", action = "Index", id = UrlParameter.Optional }
            );

然后自定一个路由类继承RouteBase  重写GetRouteData方法,然后在RouteConfig.cs中加入  routes.Add(new MyRoute());

下面是MyRoute类

using Blogs.Entity;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Blogs.UI.Main
{
    public class MyRoute : RouteBase
    {
        private Dictionary<string, RouteData> list = new Dictionary<string, RouteData>();
        //最后刷新时间
        private DateTime lastFreshDate = DateTime.Now;

        public MyRoute()
        {

        }
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            string url = httpContext.Request.Url.ToString().ToLower();
            if (url.Contains("{1}"))
            {
                return null;
            }
            if (url.Contains("browsername="))
            {
                return null;
            }

            //每10分钟刷新一次保存的路由
            if (DateTime.Now.Subtract(lastFreshDate).Minutes >= 10)
            {
                lastFreshDate = DateTime.Now;
                list.Clear();
            }

            if (list.ContainsKey(url))
            {
                return list[url];
            }

            Blogs.Entity.blog_tb_blog blog = null;
            if (httpContext.Session != null)
            {
                if (HttpContext.Current.Session["blog"] != null)
                {
                    blog = (Blogs.Entity.blog_tb_blog)HttpContext.Current.Session["blog"];
                }
                else
                {
                    blog = Utility.BlogBll.GetFirstEntity();
                    HttpContext.Current.Session["blog"] = blog;
                }
            }
            else
            {
                blog = Utility.BlogBll.GetFirstEntity();
            }

            BlogInfo info = new BlogInfo();

            info.blogID = blog.blogID;
            info.BaseUrl = url.Substring(0, url.IndexOf("/", 8));
            info.blogTitle = blog.blogTitle;
            info.blogName = blog.blogName;
            info.blogDescription = blog.blogDescription;
            info.blogKeywords = blog.blogKeywords;
            info.blogLogo = blog.blogLogo;
            info.themeName = blog.themeID;
            info.userID = blog.userID;

            return BlogRewriter(httpContext, info, url);
        }


        private RouteData BlogRewriter(HttpContextBase httpContext, BlogInfo info, string url)
        {
            RouteData result = null;
            string baseUrl = info.BaseUrl;
            #region 主页重写
            if (url == baseUrl || url == baseUrl + "/")
            {
                result = new RouteData(this, new MvcRouteHandler());
                string userAgent = httpContext.Request.ServerVariables["HTTP_USER_AGENT"];
                //ipad Safari
                //Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25
                //ipad uc
                //Mozilla/5.0 (iPad; U; CPU OS 6 like Mac OS X; zh-cn Model:iPad3,1) UC AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7543.48.3
                //android uc
                //Mozilla/5.0 (Linux; U; Android 4.0.4; zh-cn; MI 1S Build/IMM76D) UC AppleWebKit/534.31 (KHTML, like Gecko) Mobile Safari/534.31

                //if (userAgent.ToLower().Contains("android"))
                //{
                //    result.Values.Add("controller", "Mobile");
                //    result.Values.Add("action", "Index");
                //    result.Values.Add("blogInfo",info);
                //}
                //else
                //{
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
                //}
            }

            if (url == baseUrl + "/index.html")
            {
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (url == baseUrl + "/mobile.html")
            {
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Mobile");
                result.Values.Add("action", "Index");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }
            #endregion

            #region SEO
            if (Regex.IsMatch(url, baseUrl + "/sitemap.xml$", RegexOptions.IgnoreCase))
            {
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Sitemap");
                result.Values.Add("action", "Xml");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }
            if (Regex.IsMatch(url, baseUrl + "/robots.txt$", RegexOptions.IgnoreCase))
            {
                string format = @"
#
# robots.txt for {0}
#

User-agent: *
Allow: /
Sitemap:http://{0}/sitemap.xml
";
                httpContext.Response.ContentType = "text/plain";
                httpContext.Response.Write(String.Format(format, baseUrl.Replace("http://", "").Trim('/')));
                httpContext.Response.End();
            }

            if (Regex.IsMatch(url, baseUrl + "/sitemap.txt$", RegexOptions.IgnoreCase))
            {
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Sitemap");
                result.Values.Add("action", "Text");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }
            #endregion

            if (Regex.IsMatch(url, baseUrl + "/page-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/page-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("page", match.Groups[1].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/cate-\\d+-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/cate-(\\d+)-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("categoryid", match.Groups[1].Value);
                result.Values.Add("page", match.Groups[2].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/tag-\\d+-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/tag-(\\d+)-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("tagid", match.Groups[1].Value);
                result.Values.Add("page", match.Groups[2].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/month-\\d{6}-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/month-(\\d{6})-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Blog");
                result.Values.Add("action", "Index");
                result.Values.Add("month", match.Groups[1].Value);
                result.Values.Add("page", match.Groups[2].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/artic-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/artic-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Article");
                result.Values.Add("action", "Index");
                result.Values.Add("id", match.Groups[1].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/m/\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/m/(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "MShow");
                result.Values.Add("action", "Index");
                result.Values.Add("id", match.Groups[1].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            if (Regex.IsMatch(url, baseUrl + "/comment-\\w+-\\d+.html", RegexOptions.IgnoreCase))
            {
                Match match = Regex.Match(url, baseUrl + "/comment-(\\w+)-(\\d+).html");
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Comment");
                result.Values.Add("action", "Index");
                result.Values.Add("id", match.Groups[1].Value);
                result.Values.Add("page", match.Groups[2].Value);
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }


            if (Regex.IsMatch(url, baseUrl + "/rss$", RegexOptions.IgnoreCase))
            {
                result = new RouteData(this, new MvcRouteHandler());
                result.Values.Add("controller", "Rss");
                result.Values.Add("action", "Index");
                result.Values.Add("blogInfo", info);
                if (!list.ContainsKey(url))
                {
                    list.Add(url, result);
                }
                return result;
            }

            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            // return new VirtualPathData(this, "This-is-a-Test-URL");
            return null;
        }
    }
}



上一篇:wordpress3.6 修改的地方

下一篇:个人代码全部开源


0 评论

查看所有评论

给个评论吧