MVC5项目中添加Wep API

一、查看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>

二、添加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 }
            );
        }
    }
}

三、修改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);
        }
    }
}

四、添加 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:8089/Help

其实更简单的就是创建项目的时候同时选择MVC和WebAPI,以上只是我的补救措施

posted @ 2016-12-24 10:31  如果声音记得  阅读(528)  评论(0编辑  收藏  举报