当前位置 : 主页 > 网络编程 > ASP >

ASP.NETMVC对URL匹配操作

来源:互联网 收集:自由互联 发布时间:2023-01-30
1、使用{parameter}做模糊匹配 {parameter}:花括弧加任意长度的字符串,字符串不能定义成controller和action字母。默认的就是模糊匹配。 例如:{admin}。 using System;using System.Collections.Generic;u

1、使用{parameter}做模糊匹配

{parameter}:花括弧加任意长度的字符串,字符串不能定义成controller和action字母。默认的就是模糊匹配。

例如:{admin}。

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

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

            // 1、使用parameter做模糊匹配
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

2、使用字面值做精确匹配

字面值即一个常数字符串,外面不能有{}。这个字符串可以在大括弧与大括弧之间,也可以在最前面和最后面。

例如:admin/{controller}/{action}/{id}

URL1:/admin/home/index/1 可以与上面定义的路由匹配。

URL2:/home/index/1 不可以与上面定义的路由匹配(缺少字面量admin)

// 2、使用字面量做精确匹配
routes.MapRoute(
       name: "Default2",
       url: "admin/{controller}/{action}/{id}",
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

URL里面缺少admin时的运行结果:

正确的URL:

注意:这时候admin也不区分大小写。

3、不允许连续的URL参数

两个花括弧之间没有任何的字面值是不可以的(两个花括弧之间必须跟上一个固定的字母或者符合,否则无法区分是哪个参数)。

{language}-{country}/{controller}/{action}/{id} 正确

{language}{country}/{controller}/{action}/{id} 错误

// 3、不允许连续的URL参数
routes.MapRoute(
       name: "Default3",
       url: "{language}-{country}/{controller}/{action}/{id}",
       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

运行结果:

可以使用上篇文件中介绍的获取URL参数值的方式获取language和country参数的值,这里不在讲述如何获取。

4、使用*号匹配URL剩余部分

使用*来匹配URL剩余的部分,如*plus放在一个表达式的尾部,最后尾部的URL部分会保存为plus为键名的字典值。

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

在Index方法里面输出plus参数的值:

public ActionResult Index(string plus)
{
       string value = string.Format("plus={0}", plus);
       ViewData["msg"] = value;
       return View();
}

运行结果:

5、URL贪婪匹配

在URL表达式中有一种特殊的情况:就是URL表达式可能和实际的URL有多种匹配的情况,这时候遵守贪婪匹配的原则。

从上图中可以看出,贪婪匹配的原则即从后往前匹配URL。

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

在index方法里面分别获取filename和ext参数的值,并输出到页面

示例代码下载地址:点此下载

到此这篇关于ASP.NET MVC对URL匹配操作的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持自由互联。

上一篇:ASP.NETMVC扩展HtmlHelper方法
下一篇:没有了
网友评论