How to add Web API to an existing ASP.NET MVC 4 Web Application project?

I wish to add an ASP.NET Web API to an ASP.NET MVC 4 Web Application project, developed in Visual Studio 2012. Which steps must I perform to add a functioning Web API to the project? I'm aware that I need a controller deriving from ApiController, but that's about all I know.

Let me know if I need to provide more details.


The steps I needed to perform were:

  • Add reference to System.Web.Http.WebHost .
  • Add App_StartWebApiConfig.cs (see code snippet below).
  • Import namespace System.Web.Http in Global.asax.cs .
  • Call WebApiConfig.Register(GlobalConfiguration.Configuration) in MvcApplication.Application_Start() (in file Global.asax.cs ), before registering the default Web Application route as that would otherwise take precedence.
  • Add a controller deriving from System.Web.Http.ApiController .
  • I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.

    App_StartWebApiConfig.cs:

    using System.Web.Http;
    
    class WebApiConfig
    {
        public static void Register(HttpConfiguration configuration)
        {
            configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
        }
    }
    

    Global.asax.cs:

    using System.Web.Http;
    
    ...
    
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
    

    Update 10.16.2015:

    Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.


    UPDATE 11/22/2013 - this is the latest WebApi package:

    Install-Package Microsoft.AspNet.WebApi
    

    Original answer (this is an older WebApi package)

    Install-Package AspNetWebApi
    

    More details.


    To add WebAPI in my MVC 5 project.

  • Open NuGet Package manager consol and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  • Add references to System.Web.Routing, System.Web.Net and System.Net.Http dlls if not there already

  • Right click controllers folder > add new item > web > Add Web API controller

  • Web.config will be modified accordingly by VS

  • Add Application_Start(){} method if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  • Add the following class (I added in global.asax.cs file)

    public static class WebApiConfig
    {
         public static void Register(HttpConfiguration config)
         {
             // Web API routes
             config.MapHttpAttributeRoutes();
    
             config.Routes.MapHttpRoute(
                 name: "DefaultApi",
                 routeTemplate: "api/{controller}/{id}",
                 defaults: new { id = RouteParameter.Optional }
             );
         }
     }
    
  • Modify web api method accordingly

    namespace <Your.NameSpace.Here>
    {
        public class VSController : ApiController
        {
            // GET api/<controller>   : url to use => api/vs
            public string Get()
            {
                return "Hi from web api controller";
            }
    
            // GET api/<controller>/5   : url to use => api/vs/5
            public string Get(int id)
            {
                return (id + 1).ToString();
            }
        }
    }
    
  • Rebuild and test

  • Build a simple html page

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>    
        <script src="../<path_to_jquery>/jquery-1.9.1.min.js"></script>
        <script type="text/javascript">
            var uri = '/api/vs';
            $(document).ready(function () {
                $.getJSON(uri)
                .done(function (data) {
                    alert('got: ' + data);
                });
    
                $.ajax({
                    url: '/api/vs/5',
                    async: true,
                    success: function (data) {
                        alert('seccess1');
                        var res = parseInt(data);
                        alert('got res=' + res);
                    }
                });
            });
        </script>
    </head>
    <body>
    ....
    </body>
    </html>
    
  • 链接地址: http://www.djcxy.com/p/3452.html

    上一篇: 设置默认的WebAPI格式化程序

    下一篇: 如何将Web API添加到现有的ASP.NET MVC 4 Web应用程序项目?