如何向MVC5项目中添加Wep API

来源:互联网 发布:淘宝开店一定要交保证金吗 编辑:程序博客网 时间:2024/06/02 00:36

近来学习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,以上只是我的补救措施