ASP.NET MVC 源代码 剖析
ASP.NET MVC 里面其實是在原來的ASP.NET 基礎之上,通過用UrlRoutingModule和MvcHttpHandler來替換了原來web Form處理方式的。
UrlRoutingModule 微軟沒有開源的,但是我們可以來分析下MvcHttpHandler
實現了:IHttpHandler接口
? #region IHttpHandler Members
??????? bool IHttpHandler.IsReusable {
??????????? get {
??????????????? return IsReusable;
??????????? }
??????? }
??????? void IHttpHandler.ProcessRequest(HttpContext httpContext) {
??????????? ProcessRequest(httpContext); //有點像適配器模式
??????? }
??????? #endregion
//MVC真正處理請求的方法
? protected virtual void ProcessRequest(HttpContext httpContext) {
??????????? HttpContextBase iHttpContext = new HttpContextWrapper(httpContext);?//通過httpContext上下文,初始化一個MVC環境中的上下文
??????????? ProcessRequest(iHttpContext);
??????? }
?
?protected internal virtual void ProcessRequest(HttpContextBase httpContext) {
??????????? AddVersionHeader(httpContext);
??????????? // Get the controller type
??????????? string controllerName = RequestContext.RouteData.GetRequiredString("controller");? //?? 這個代碼的意思就是根據當前上下文,找出controller類
??????????? // Instantiate the controller and call Execute
??????????? IControllerFactory factory = ControllerBuilder.GetControllerFactory();? //實例化一個controller類型工廠,運用了抽象工廠模式
??????????? IController controller = factory.CreateController(RequestContext, controllerName);? //工廠方法
??????????? if (controller == null) {
??????????????? throw new InvalidOperationException(
??????????????????? String.Format(
??????????????????????? CultureInfo.CurrentUICulture,
??????????????????????? MvcResources.ControllerBuilder_FactoryReturnedNull,
??????????????????????? factory.GetType(),
??????????????????????? controllerName));
??????????? }
??????????? try {
??????????????? controller.Execute(RequestContext);?? //輸入MVC上下文對象,處理邏輯,找到Model,選擇View,最終實現請求,
??????????? }
??????????? finally {
??????????????? factory.ReleaseController(controller);? //釋放資源
??????????? }
??????? }
?
可以看到ASP.NET MVC 并不神秘,只是在MvcHandler 這個類里面做了一些處理,明白了這些,我們就可以自己在擴展一些東西,比如
自己在繼承MvcHandler類。
?
至于MVC 的View 部分,其實就是另外一套 輸入HTML的技術。
看看View的父類ViewPage : Page, IViewDataContainer? 繼承了這2個東西
在看看接口IViewDataContainer? :
ViewDataDictionary ViewData { get; set; }? 從字面意識可以知道是 數據字典 ,也就是 View頁面上展示的數據 就是來自于這個ViewDataDictionary
在看看 ViewDataDictionary? 里面的代碼,注意到有這么一個Dictionary<string, object> _innerDictionary 對象,內嵌泛型字典。
呵呵,現在我們就知道在View頁面上怎么 綁定數據了,比如
?<h2><%= Html.Encode(ViewData["Message"]) %></h2>? 這下就知道了 什么意思了撒,Message就是 數據的一個key值,要什么數據只需要曉得
他的Key值,便能知道他的數據。
?
呵呵,通過以上代碼的 分析,大概你也明白了,ASP MVC是個什么樣子的,你也許會認為這不過是微軟 的一個騙術罷了,并沒有什么高明的,
反而失去了,服務器控件的一些優點,我覺得總的來說 還是 缺點大與 優點。
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/woaixueyu/archive/2009/05/27/1491007.html
總結
以上是生活随笔為你收集整理的ASP.NET MVC 源代码 剖析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 本地连接没有图标
- 下一篇: .NET:如何声明某个程序需要管理员权限