如何在現有 ASP.NET MVC 5 專案上加入 ASP.NET Web API
如果你已經建立好一個 ASP.NET MVC 5,而又突然想要加入 ASP.NET Web API 2 的相關套件與設定檔,你可以參考本篇文章解說的 SOP 進行設定。所有步驟也都以 Git 進行版控,各位可以到 https://github.com/doggy8088/MVC5_Add_WebAPI 查閱每個步驟的變更紀錄。
1. 先將 ASP.NET MVC 5 升級到最新版,並檢查 web.config 中的 <runtime> 設定
Update-Package Microsoft.AspNet.Mvc
在 web.config 檔案中先找到以下設定
<dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" /> </dependentAssembly>
然後修改成正確的 ASP.NET MVC 5 版本編號 (可參考 packages.config 中的版本號)
<dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" /> </dependentAssembly>
2. 安裝 ASP.NET Web API 相關套件 (請利用套件管理員主控台輸入以下指令)
Install-Package Microsoft.AspNet.WebApi Install-Package Microsoft.AspNet.WebApi.Client.zh-Hant Install-Package Microsoft.AspNet.WebApi.Core.zh-Hant Install-Package Microsoft.AspNet.WebApi.WebHost.zh-Hant
3. 新增 /App_Start/WebApiConfig.cs 檔案,並填入以下程式碼
※ 請注意 namespace 要修改成你目前專案的預設命名空間!
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace MVC5 { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 設定和服務 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
4. 修改 Global.asax.cs 檔案,註冊 ASP.NET Web API 相關設定
在 Global.asax.cs 檔案最上方引用 System.Web.Http 命名空間
using System.Web.Http;
在 Application_Start() 方法中的 AreaRegistration.RegisterAllAreas(); 這行下方加入以下程式碼
GlobalConfiguration.Configure(WebApiConfig.Register);
我個人通常會多加上這行,因為我幾乎用不到 XML 格式輸出:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
5. 如果你要安裝 ASP.NET Web API 線上說明文件的話,可直接安裝 Microsoft.AspNet.WebApi.HelpPage 套件,所有相關檔案與 Area 都會自動建立完成
Install-Package Microsoft.AspNet.WebApi.HelpPage
資料來源: https://blog.miniasp.com/post/2015/02/18/How-to-Add-Web-API-to-ASPNET-MVC.aspx
留言
張貼留言