ASP.NET MVC 学习之路由(URL Routing)

在ASP.NET MVC中,一个URL请求是由对应的一个Controller中的Action来处理的,由URL Routing来告诉MVC如何定位到正确的Controller和Action。

默认路由表 

当我们在VS中创建一个新的 ASP.NET MVC程序,程序将会自动使用默认的路由表。

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

            routes.MapRoute(
                name: "Default",//默认路由名称
                url: "{controller}/{action}/{id}",//URL 和参数
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }//默认参数
            );
        }

上面的代码是向路由表添加一个名为(Default)的路由。

url 中

{controller} 对应的也就是控制器名称,

{action} 对应的是控制器中的action,

{id} 对应为参数,

defaults 为默认值 controller = "Home"  action = "Index" 。

当你在地址栏输入/Home 因为action 有对应的默认值 ,程序也就会执行HomeController.Index()。

当你在地址栏输入/Home/Index/6 时,路由会自动对应参数

controller = Home

action = Index

id = 6

程序也就会去执行 HomeController.Index(6)。

示例展示:

 

上面的静态方法RegisterRoutes是在Global.asax.cs文件中的Application_Start方法中被调用的。

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

namespace MvcApplication
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

同时也包含了其他的一些方法。

自定义路由表

 下面增加一个自己定义的路由表

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

            routes.MapRoute(
                name: "Default",//默认路由名称
                url: "{controller}/{action}/{id}",//URL 和参数
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },//默认参数
                constraints: new { action = @"[a-zA-Z]+" }//只匹配字母
            );

            routes.MapRoute(
                name: "MyRoute",//路由名称
                url: "News/{newsid}",//URL不带参数
                defaults: new { controller = "News", action = "Index" },//默认指定action到Index
                constraints: new { newsid = @"d+" }//newsid必须为数字
            );
        }

当你在地址栏输入/News/Index?newsid=1 和 /News/1 效果是一样的。

访问/News/1 它会默认 访问 controller=News  action=Index 然后参数为1 。

我把默认的路由规则,加了一下限制,让其action 只执行字母,以免覆盖新加的路由规则。

这样我们可以缩短URL 地址,让URL 更加直观友好。

路由约束:

正则表达式约束

通过正则来约束相关路由规则。

routes.MapRoute(
                name: "MyRoute",//路由名称
                url: "News/{newsid}",//URL不带参数
                defaults: new { controller = "News", action = "Index" },//默认指定action到Index
                constraints: new { newsid = @"d+" }//newsid必须为数字
            );

上面为约束 newsid为 数字。

routes.MapRoute(
                name: "Default",//默认路由名称
                url: "{controller}/{action}/{id}",//URL 和参数
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },//默认参数
                constraints: new { action = @"[a-zA-Z]+" }//只匹配字母
            );

上面为约束 action 只为字母,不允许其他规则。

Http请求方式约束

            routes.MapRoute(
                name: "MyRoute",//路由名称
                url: "News/{newsid}",//URL不带参数
                defaults: new { controller = "News", action = "Index" },//默认指定action到Index
                constraints: new { newsid = @"d+", httpMethod = new HttpMethodConstraint("POST") }//newsid必须为数字 并且请求必须为POST
            );

上面为约束 http请求 为POST

自定义路由约束

 如果标准的路由约束满足不了你的需求,那么可以通过实现 IRouteConstraint 接口来定义自己的路由约束规则。

下面就是实现了一个请求是否来自本地的约束。

public class LocalhostConstraint : IRouteConstraint
    {
        public bool Match
            (
                HttpContextBase httpContext,
                Route route,
                string parameterName,
                RouteValueDictionary values,
                RouteDirection routeDirection
            )
        {
            return httpContext.Request.IsLocal;
        }
    }

在路由表中的应用:

routes.MapRoute(
                name: "Default",//默认路由名称
                url: "{controller}/{action}/{id}",//URL 和参数
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },//默认参数
                constraints: new { action = @"[a-zA-Z]+", isLocal = new LocalhostConstraint() }//只匹配字母 并且请求只允许本地
            );

上面为约束 http请求 来自本地。

示例代码下载

如果你觉得本文对你有帮助,请点击“推荐”,谢谢。

原文地址:https://www.cnblogs.com/linezero/p/4999741.html