近來學習MVC,已經能試着顯示一個列表了(真實數據),想到一個網站的首頁會有很多列表,如何操作呢?某人提醒我用API+jQuery顯示數據。
一、查看MVC版本,決定你有沒有必要看這篇文章
打開web.config,看到以下內容
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
- 1
- 2
- 3
- 4
- 1
- 2
- 3
- 4
二、添加Controller
Controller文件夾 右擊-添加-Web API控制器(v2.1),建好後,系統自動創建以下文件:
App_Start/WebApiConfig.cs(沒有請添加)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace FirstMvc5
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
三、修改Global.asax.cs
打開Global.asax.cs,添加:GlobalConfiguration.Configure(WebApiConfig.Register);
完整代碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;
namespace FirstMvc5
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
四、添加 WebAPI Help
(本部分內容來源微軟官方:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages)
從工具菜單中,選擇NuGet包管理器,然後選擇程序包管理器控制檯。在程序包管理器控制檯窗口中,鍵入下列命令之一 ︰
C#應用程序 ︰Install-Package Microsoft.AspNet.WebApi.HelpPage
Visual Basic應用程序 ︰Install-Package Microsoft.AspNet.WebApi.HelpPage.VB
自動添加了Areas文件夾
五、大功告成
生成,預覽http://xxx:20836/Help
其實更簡單的就是創建項目的時候同時選擇MVC和WebAPI,以上只是我的補救措施