本章将讲述ASP.NET MVC5 的路由原理,即URL映射机制。
简单点就是解释:为什么MVC在浏览器输入地址就能访问到类(或类中的方法)?这是怎么做到的?我自己可以通过.NET写出一个自己的MVC框架吗?
答案是:可以。
先来看一个Demo,在传统的.NET WebForms项目中,实现URL的拦截。
打开VS2013,新建一个“ASP.NET Web窗体应用程序”项目,并取名为Demo4URLRouting。
为了方便测试,注释掉Default.aspx页面的内容和模板引用。这样做以后,看起来是这样
然后新建一个ControllerFactory类,实现IHttpHandler接口。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace Demo4URLRouting 7 { 8 /// <summary> 9 /// 自己写的ControllerFactory,试图扮演MVC5中的RouteConfig(路由配置)角色。 10 /// </summary> 11 public class ControllerFactory : IHttpHandler 12 { 13 ControllerFactory() 14 { 15 } 16 17 public bool IsReusable 18 { 19 get; 20 set; 21 } 22 23 public void ProcessRequest(HttpContext context) 24 { 25 context.Response.Write(string.Format("ControllerFactory来拦截请求-> URL为: {0}",context.Request.RawUrl)); 26 } 27 } 28 }