欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net mvc重写url地址

程序员文章站 2023-12-29 09:49:10
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WebGrease.Css.Ast;

namespace WebApplicationUrlWrite
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //加载重写
            routes.Add(new MyRoute());

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

    public class MyRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            return null;

            //var virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath + httpContext.Request.PathInfo;//获取相对路径
            //var data = new RouteData(this, new MvcRouteHandler());//声明一个RouteData,添加相应的路由值
            //data.Values.Add("controller", "Category");
            //data.Values.Add("action", "ShowCategory");
            //data.Values.Add("id", 1);

            //return null;//返回这个路由值将调用CategoryController.ShowCategory(category.CategoeyID)方法。匹配终止
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            string token = requestContext.HttpContext.Request.QueryString["uck"];
            string controller = values["controller"].ToString();
            string action = values["action"].ToString();

            //处理Html.Action传递多参数
            //<a href="@Url.Action("About","home",new{articleId= "asldjfsjd", phone = "13588877234" , address = "武侯大道" ,pageIndex=1,pageSize=10})">关于2</a>
            StringBuilder sb = new StringBuilder();
            foreach (var item in values.Keys)
            {
                if (item.Equals("controller") || item.Equals("action"))
                {
                    continue;
                }
                var _kvalue = values[item];
                sb.Append("&" + item + "=" + _kvalue);
            }
            string url = controller + "/" + action + "?uck=" + token + sb.ToString();
            return new VirtualPathData(this, url);
        }
    }

}

 

查看生成url:

asp.net mvc重写url地址

 

 

 

 

相关标签: ASP.NET MVC

上一篇:

下一篇: