C# MVC匹配URL多样性和正则表达式用法

混江龙づ霸主 提交于 2019-12-07 18:09:54
 public ActionResult Login()//VirtualPathData可获取浏览器响应URL
        {
            VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "Default", new RouteValueDictionary(new { controller = "Users", action = "Login" }));
            return View();
        }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcMySchool
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)//多种路由匹配和正则表达式用法
        {
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

             routes.MapRoute(
                name: "Default",
                url: "www.hetengfei.com/{controller}/{action}" //使用字面值做精确匹配
            );
            routes.MapRoute(
               name: "Default1",
               url: "{state}-{are}/{controller}/{action}/{id}"  //使用不连续的URL参数
           );
            routes.MapRoute(
            "Default2", 
            "{controller}/{action}/{foo}xyz{bar}" // 使用不连续的URL参数
            );
            routes.MapRoute(
                name: "Default3",
                url: "{controller}/{action}/{id}"      //正常匹配
            );
            routes.MapRoute(
               "Default4",
               "{controller}/{action}/{year}/{month}/{day}",
               new { year = @"\d{4}", month = new MonthConstraint(), day = @"\d{2}" }  // 带有正则表达式 URL

               ); // 参数默认值
            routes.MapRoute(
               name: "Default5",
               url: "{controller}/{action}/{id}/{*pind}",      //使用*匹配剩余部分URL
               defaults: new { controller = "Users", action = "Login", id = UrlParameter.Optional }
           );
        }
    }
    public class MonthConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (values["month"].ToString().Length == 2
                && Convert.ToInt32(values["month"]) >= 1
                && Convert.ToInt32(values["month"]) <= 12)
                return true;

            return false;
        }
    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!