2013年1月6日 星期日

ASP.NET Web Forms 專案加入 ASP.NET MVC 4

ASP.NET MVC 與 Web Forms 的開發在前端展現處理上是有很大的差異,但是資料處理、商業邏輯的部份卻是沒有什麼不同的(當然這邊不包括說在 Web Forms 裡有人會使用到的 DataSource 控制項,基本上我開發 Web Forms 已經不用這些 DataSource 控制項),所以我們可以嘗試在 Web Forms 網站專案中加入 ASP.NET MVC,讓 Web Forms 與 MVC 共存在一個網站專案中,這樣的整合方式並不適合 ASP.NET MVC 的初學者,這一篇適合已經熟悉 ASP.NET Web Forms 並且也已經對於 ASP.NET MVC 開發相當熟悉的開發人員,對 ASP.NET Web Forms 還不熟悉或是只熟悉 ASP.NET Web Forms 開發並且對 ASP.NET MVC 完全不了解或是尚未熟悉的人,這一篇就請先跳過。

不過 ASP.NET Web Forms 4.5 專案要加入 APS.NET MVC 4 並不是一件容易的事情,事前會有一堆的設定需要調整,在本篇文章中將會位大家說明要如何完成這些的設定。

 


開發環境:Visual Studio 2012

使用版本:ASP.NET Web Forms 4.5, ASP.NET MVC 4

 

1. 建立 ASP.NET Web Forms 4.5 網站專案

image

主要的工作區,在這個專案中增加 ASP.NET MVC。

 

2. 建立 ASP.NET MVC 4 網站專案

image

這個 MVC 網站專案是用來對照用的,看看有什麼是需要加入 Web Forms 網站專案中。

 

3. Web Forms 專案加入 ASP.NET MVC 參考

image

左邊是 MVC 專案,右邊是 Web Forms 專案,Web Forms 專案的參考裡要加入 MVC 的哪些必要參考,整理如下:

  • System.Web.Helpers 2.0.0.0
  • System.Web.Mvc 4.0.0.0
  • System.Web.Razor 2.0.0.0
  • System.Web.Routing 4.0.0.0
  • System.Web.WebPages 2.0.0.0
  • System.Web.WebPages.Razor 2.0.0.0
  • image

     

    4. 修改 Web Forms 網站專案的 Web.Config 內容

    接著就是要修改 Web Forms 專案裡的 Web.Config,這時候就同時開啟 MVC 專案的 Web.Config 與 We Forms 專案的 Web.Config,然後把 MVC 需要用到的設定內容複製到 Web Forms 專案的 Web.Config 中,建議可以使用 Code Compare 或其他的檔案比對工具,

    image

    就每一個 Section 來做說明,

    appSettings

    如果沒有 appSettings Section 就請增加以下的內容,或是已經有 appSettings 就增加以下的內容:

    <appSettings>
        <add key="webpages:Version" value="2.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>

    system.web

    在 system.web section 內的 pages 要增加以下的內容:

    <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
    </namespaces>
    image

    system.webServer

    增加以下的內容:

    <system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      </handlers>
    </system.webServer>

    runtime

    在 runtime section 的 assemblyBinding 裡增加以下的內容:

    <dependentAssembly>
      <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
      <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
      <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
      <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
    </dependentAssembly>

    另外建議在完成上面的動作之後可以使用 NuGet 安裝「Microsoft ASP.NET MVC 4」套件。

    SNAGHTMLa21f654

    將 Web Forms 專案的 Web.Config 完成以上的修改並且儲存完畢後,先把 Web Forms 專案關閉,然後開啟 Web Forms 專案的資料夾中,再來進行接下來的步驟。

     

    5. 修改 Web Forms 專案的 csproj 檔案內容

    開啟 Web Forms 專案的 csproj 檔案後也另外開啟 MVC 專案的 csproj 檔案,要修改 csproj 檔案內容的原因是要增加「ProjectTypeGiuids」的內容,將 MVC 的 ProjectTypeGuid 增加到 Web Forms 專案 csproj,如此一來在 Web Forms 專案裡的右鍵選單裡就會有增加 Controller 或 View 的項目,

    image

    上圖裡,上方是 Web Forms 專案的 csproj 檔案,下方是 MVC 專案的 csproj 檔案,兩邊的 ProjectTypeGuids 內容的差別在於 MVC 的 csproj 多了「{E3E379DF-F4C6-4180-9B81-6769533ABE47};」,我們就把這個 ProjectTypeGuid 值加入到 Web Forms 的 csproj 中,

    image

    內容修改完畢並儲存後關閉檔案,然後重新開啟 Web Forms 專案。

     

    6. Web Forms 專案加入 App_Start 目錄內的檔案

    預設建立 ASP.NET Web Forms 4.5 網站專案時就會建立「App_Start」目錄,

    image

    而 ASP.NET MVC 4 網站專案的 App_Start 目錄內有些檔案是 Web Forms 網站專案所沒有的,

    image

    這邊我們把 MVC 專案 App_Start 目錄內的「FilterConfig.cs, RouteConfig.cs, WebApiConfig.cs」這三個檔案給複製到 Web Forms 專案的 App_Start 目錄下,

    image

    複製完畢後,還必須修改這三個檔案裡的 Namespace,如下,

    image

    修改 Namespace,使用與 Web Forms 專案 App_Start 目錄裡原本檔案裡相同的 Namespace,

    image

    在完成三個新增檔案的命名空間修改後,重新建置方案卻出現建置錯誤的訊息,這是因為沒有加入 ASP.NET WebApi 的緣故。

    image

     

    7. 使用 NuGet 加入 ASP.NET Web API

    開啟 NuGet,搜尋「ASP.NET Web API」並安裝,

    SNAGHTML9d12e63

    安裝 ASP.NET Web API 之後重建專案,如果還有出現以下的錯誤,「'System.Web.Http.HttpConfiguration' 不包含 'EnableQuerySupport' 的定義,也找不到擴充方法 'EnableQuerySupport' 來接受型別 'System.Web.Http.HttpConfiguration' 的第一個引數 (您是否遺漏 using 指示詞或組件參考?)

    image

    這時候必須在 NuGet 裡搜尋「ASP.NET WebAPI OData」發行前版本,然後選擇安裝,

    SNAGHTML9d9a556

    安裝過後再重新建置方案就可以建置成功,加入 ASP.NET WebAPI 以及 ASP.NET WebAPI OData 是要 Web Forms 專案參考有以下的組件,

    image

    System.Web.Http 與 System.Web.Http.WebHost 是可以在參考管理員裡從 GAC 找到,

    SNAGHTML9ec6f49

    System.Web.Http.OData 無法從參考管理員裡面找到,而必須從 NuGet 裡去搜尋發行前版本才能找到。

     

    8. 修改 Global.asax

    對照著 MVC 網站專案的 Global.asax 內容,將 Web Forms 網站專案 Global.asax 的 Application_Start() 增加以下的程式內容,
    image

    void Application_Start(object sender, EventArgs e)
    {
        AreaRegistration.RegisterAllAreas();
     
        // 應用程式啟動時執行的程式碼
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
     
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterOpenAuth();
    }

     

    9. 增加 MVC 的區域及內容

    網路上找到很多類似 Web Forms 網站整合 MVC 的文章,大多數文章的最後都是告訴我們直接在 Web Forms 專案目錄下直接新增「Controllers」與「Views」目錄,但我覺得這樣的方式相當不好,畢竟 Web Forms 與 MVC 的檔案是有差異的,還是必須要做個區分,而區分的最好作法就是使用 ASP.NET MVC 的 Area,以 Area 的方式在 Web Forms 專案中建立 MVC,這樣一來 Web Forms 與 MVC 就不會有混淆與不容易管理的情況,

    建立 Area(區域)

    image

    建立「Test」區域,

    image

    接著把 MVC 專案內 Shared 目錄下的檔案複製一份到 Test 區域的 Shared 目錄裡,比較重要的檔案有:_Layout.cshtml 與 _ViewStart.cshtml

    image

     

    10. 修改區域內 Views/Web.Config

    另外我們還需要修改 Test 區域裡 Views 目錄裡的 Web.Config 內容,不然在區域的 View Page 的 Razor ViewEngine 會無法正常使用,如下,

    image

    先開啟 Test 區域的 Views / Web.Config 檔案

    image

    要將上面紅色框線裡的 ConfigSections 內容以下面的內容做替換,

    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="System.Web.Mvc.WebViewPage">
            <namespaces>
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Optimization"/>
                <add namespace="System.Web.Routing" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>

    修改後

    image

    重新建置方案後,開啟 View Page 然後使用 Razor Syntax 輸入 HtmlHelper,可以看到可以正常使用,

    image

    其實比較快的方式是把 MVC 網站專案裡 Views 目錄下的 Web.Config 內容全部複製,然後將 Test 區域裡 Views 目錄內的 Web.Config 替換,

    <?xml version="1.0"?>
     
    <configuration>
        <configSections>
            <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
                <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            </sectionGroup>
        </configSections>
     
        <system.web.webPages.razor>
            <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <pages pageBaseType="System.Web.Mvc.WebViewPage">
                <namespaces>
                    <add namespace="System.Web.Mvc" />
                    <add namespace="System.Web.Mvc.Ajax" />
                    <add namespace="System.Web.Mvc.Html" />
                    <add namespace="System.Web.Optimization"/>
                    <add namespace="System.Web.Routing" />
                </namespaces>
            </pages>
        </system.web.webPages.razor>
     
        <appSettings>
            <add key="webpages:Enabled" value="false" />
        </appSettings>
     
        <system.web>
            <httpHandlers>
                <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
            </httpHandlers>
     
            <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
            <pages
                validateRequest="false"
                pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
                pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
                userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                <controls>
                    <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
                </controls>
            </pages>
        </system.web>
     
        <system.webServer>
            <validation validateIntegratedModeConfiguration="false" />
     
            <handlers>
                <remove name="BlockViewHandler"/>
                <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
            </handlers>
        </system.webServer>
    </configuration>

     

    11. 修改 Test 區域的 _ViewStart.cshtml 內容

    我們從 MVC 網站專案所複製的 _ViewStart.cshtml 內容如下,

    image

    上面的 Layout 所指的路徑是根目錄下,但因為 WebForms 網站專案下的 MVC 是建立在 Test 區域下,所以必須要修改 _ViewStart.cshtml 的 Layout 路徑位置,修改後的 layout 路徑如下,

    image

     

    12. 增加 MVC 區域所使用的 Content 檔案(Site.css)

    接著把 MVC 網站專案內的 Content 內容給複製到 WebForms 網站專案的 Content 目錄內,但因為 WebForms 網站專案原本就已經有 Site.css 與 themes 目錄,為了區別,所以就在 Content 目錄下另外建立子目錄「Mvc」,把從 MVC 網站專案複製過來的檔案放置到 Content / Mvc 目錄裡,

    image

    接著再把 Content / Mvc / Site.css 內容的圖片路徑做修改,例如:

    image

     

    13. 修改 BundleConfig 內容

    在 ASP.NET Web Forms 4.5 後也增加了 App_Start 內的 BundleConfig.cs 檔案,其內容如下,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Optimization;
     
    namespace WebForms_and_MVC4
    {
        public class BundleConfig
        {
            // 如需統合的詳細資訊,請造訪 http://go.microsoft.com/fwlink/?LinkId=254726
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
                      "~/Scripts/WebForms/WebForms.js",
                      "~/Scripts/WebForms/WebUIValidation.js",
                      "~/Scripts/WebForms/MenuStandards.js",
                      "~/Scripts/WebForms/Focus.js",
                      "~/Scripts/WebForms/GridView.js",
                      "~/Scripts/WebForms/DetailsView.js",
                      "~/Scripts/WebForms/TreeView.js",
                      "~/Scripts/WebForms/WebParts.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));
     
                // 使用 Modernizr 的開發版本來開發並深入了解。當您準備好量產時,
                // 請使用 http://modernizr.com 中的建置工具來挑選出您需要的測試
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));
     
            }
        }
    }

    而 ASP.NET MVC 4 的 BundleConfig.cs 內容如下,

    using System.Web;
    using System.Web.Optimization;
     
    namespace Mvc4Application
    {
        public class BundleConfig
        {
            // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                            "~/Scripts/jquery-ui-{version}.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.unobtrusive*",
                            "~/Scripts/jquery.validate*"));
     
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
     
                bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
     
                bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                            "~/Content/themes/base/jquery.ui.core.css",
                            "~/Content/themes/base/jquery.ui.resizable.css",
                            "~/Content/themes/base/jquery.ui.selectable.css",
                            "~/Content/themes/base/jquery.ui.accordion.css",
                            "~/Content/themes/base/jquery.ui.autocomplete.css",
                            "~/Content/themes/base/jquery.ui.button.css",
                            "~/Content/themes/base/jquery.ui.dialog.css",
                            "~/Content/themes/base/jquery.ui.slider.css",
                            "~/Content/themes/base/jquery.ui.tabs.css",
                            "~/Content/themes/base/jquery.ui.datepicker.css",
                            "~/Content/themes/base/jquery.ui.progressbar.css",
                            "~/Content/themes/base/jquery.ui.theme.css"));
            }
        }
    }

    我們要把 ASP.NET MVC 4 的 BundleConfig.cs 的內容做適度的修改(路徑),然後再複製到 WebForms 專案的 BundleConfig.cs 內,另外也要將一些 Script 檔案也複製到 WebForms 專案的 Scripts 目錄下,

    image

    修改後的 WebForms 專案 BundleConfig.cs 內容,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Optimization;
     
    namespace WebForms_and_MVC4
    {
        public class BundleConfig
        {
            // 如需統合的詳細資訊,請造訪 http://go.microsoft.com/fwlink/?LinkId=254726
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/WebFormsJs").Include(
                      "~/Scripts/WebForms/WebForms.js",
                      "~/Scripts/WebForms/WebUIValidation.js",
                      "~/Scripts/WebForms/MenuStandards.js",
                      "~/Scripts/WebForms/Focus.js",
                      "~/Scripts/WebForms/GridView.js",
                      "~/Scripts/WebForms/DetailsView.js",
                      "~/Scripts/WebForms/TreeView.js",
                      "~/Scripts/WebForms/WebParts.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/MsAjaxJs").Include(
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjax.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxApplicationServices.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxTimer.js",
                    "~/Scripts/WebForms/MsAjax/MicrosoftAjaxWebForms.js"));
     
                // 使用 Modernizr 的開發版本來開發並深入了解。當您準備好量產時,
                // 請使用 http://modernizr.com 中的建置工具來挑選出您需要的測試
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));
     
                
                // MVC 4 BundleCoinfig
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                            "~/Scripts/jquery-ui-{version}.js"));
     
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.unobtrusive*",
                            "~/Scripts/jquery.validate*"));
     
                bundles.Add(new StyleBundle("~/Content/MvcCss").Include("~/Content/Mvc/site.css"));
     
                bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                            "~/Content/Mvc/themes/base/jquery.ui.core.css",
                            "~/Content/Mvc/themes/base/jquery.ui.resizable.css",
                            "~/Content/Mvc/themes/base/jquery.ui.selectable.css",
                            "~/Content/Mvc/themes/base/jquery.ui.accordion.css",
                            "~/Content/Mvc/themes/base/jquery.ui.autocomplete.css",
                            "~/Content/Mvc/themes/base/jquery.ui.button.css",
                            "~/Content/Mvc/themes/base/jquery.ui.dialog.css",
                            "~/Content/Mvc/themes/base/jquery.ui.slider.css",
                            "~/Content/Mvc/themes/base/jquery.ui.tabs.css",
                            "~/Content/Mvc/themes/base/jquery.ui.datepicker.css",
                            "~/Content/Mvc/themes/base/jquery.ui.progressbar.css",
                            "~/Content/Mvc/themes/base/jquery.ui.theme.css"));
            }
        }
    }

    然後也需要修改 WebForms 專案 Scripts 目錄下的 _References.js 內容,

    image

     

    最後執行結果

    經過上面一連串的修改後,執行網站來做驗證,一開始執行網站是顯示 WebForms 的起始頁,

    SNAGHTMLd8ab34e

    再來就是檢查 WebForms 網站專案內的 MVC 是否可以正常執行,

    SNAGHTMLd8b57d6

    再來檢查 Bundle 的 CSS 與 Javascript 是否正常,

    SNAGHTMLd8cbec3

    初步檢查過後,看來大致上的功能與顯示都很正常,就這樣我們完成了在 ASP.NET Web Forms 4.5 的網站專案下整合 ASP.NET MVC 4 的工作。

     


    ASP.NET Web Forms 4.5 要整合 ASP.NET MVC 4 看起來一件不是一件簡單的工程,而且上面所說明的幾個步驟也只是初期的基本工程而已,兩者要做到更好的整合還有很多工程需要做到,例如系統架構要做到分層設計,商業邏輯與頁面顯示邏輯要完全切開(這對於 Web Forms 專案來說,很多開發者無法做到這一點),所以基本的整合工程做完之後還需要很多測試與驗證的工作要做。

    ASP.NET Web Forms 4.5 與 ASP.NET MVC 4 有很多的功能更新與改版,而 ASP.NET Web Forms 4 整合 ASP.NET MVC 3 就比較不會這麼複雜了,所以之後有機會再來說明 ASP.NET Web Forms 4 與 ASP.NET MVC 3 的整合。

    P.S.
    ASP.NET Web Forms 專案加入 MVC 後,不要以為這樣就可以在 MVC 裡去使用 Server Controls,完全不建議這麼做,所以我不會說明這個部分,另外我也不會另外去說明 ASP.NET MVC 專案如何加入 ASP.NET Web Forms,因為那樣對我來說是沒有意義的,因為我是推廣大家使用 ASP.NET MVC 來開發。

     

    參考連結:

    Programming ASP.NET MVC 4  - Appendix A. ASP.NET MVC and Web Forms Integration
    http://ofps.oreilly.com/titles/9781449320317/ch_MVCandWebForms.html

    Falafel Software Blog Site - Integrating ASP.NET MVC 4 into Existing Web Forms Applications
    http://blog.falafel.com/Blogs/BasemEmara/basem-emara/2012/09/27/integrating-asp.net-mvc-4-into-existing-web-forms-applications

     

    以上

    6 則留言:

    1. 這樣混合的目的是什麼?要解決什麼問題?

      回覆刪除
      回覆
      1. 有時後某些功能已經用 MVC 寫好了,並不想在 WebForms 專案重寫一次時,
        我之前有遇到過,因為有個功能式已經用 MVC 2 寫好,但並不想在 WebForms 專案重寫一次,就會這麼方法,
        不過之前都是 MVC2 or MVC3 放到 WebForms 專案。

        刪除
    2. 作者已經移除這則留言。

      回覆刪除
    3. I've copy carefully your behavior to create my flatform, but it show the error following brewing.
      請問一下,當執行的時候,他使用的config file 將會是根目錄的還是View file內的
      感謝...
      我的Mail是 yes302@gmail.com
      -------

      詳細錯誤資訊:
      模組 IIS Web Core
      通知 不明
      處理常式 尚未判定
      錯誤碼 0x8007000d
      設定錯誤 只允許一個 元素。它必須是 根元素的第一個子元素
      設定檔案 \\?\C:\src\otgapp\OTGApp\web.config
      要求的 URL http://localhost:54306/Service/Combined/PostServer.aspx
      實體路徑
      登入方法 尚未判定
      登入使用者 尚未判定
      要求追蹤目錄 C:\Users\TommyHsu\Documents\IISExpress\TraceLogFiles\


      設定來源:

      34:
      35:
      36:
      -----

      以上再麻煩Mrkt大回覆了...
      小弟若有任何可以update的,在來回覆...

      回覆刪除
      回覆
      1. 依照這篇文章的例子來說,WebForm 專案裡包含 MVC 專案,所以 MVC 專案會使用到外部 WebForm 的 Web.Config,
        而 MVC 專案裡 Views 目錄下的 Web.Cinfig 是給 View 檔案所使用的,這兩個有所區分。

        所以「4. 修改 Web Forms 網站專案的 Web.Config 內容」這個步驟就是要讓 WebForm 專案裡的 MVC 可以正常使用。
        然後「10. 修改區域內 Views/Web.Config」這個步驟則是要讓 WebForm 專案裡的 MVC View 可以正常使用 Razor ViewEngine。

        至於你所貼出來的錯誤訊息,我就毫無頭緒,因為不曉得你有改了什麼或是漏了什麼,也不清楚你的專案版本,
        如果是 ASP.NET MVC 5 與 ASP.NET WebForm 4.5 整合的話,這樣的狀況就會有所不同了,這部份就沒有研究過了。

        刪除
    4. 網誌管理員已經移除這則留言。

      回覆刪除

    提醒

    千萬不要使用 Google Talk (Hangouts) 或 Facebook 及時通訊與我聯繫、提問,因為會掉訊息甚至我是過了好幾天之後才發現到你曾經傳給我訊息過,請多多使用「詢問與建議」(在左邊,就在左邊),另外比較深入的問題討論,或是有牽涉到你實作程式碼的內容,不適合在留言板裡留言討論,請務必使用「詢問與建議」功能(可以夾帶檔案),謝謝。