asp.net-mvc 如何将 Web API 添加到现有的 ASP.NET MVC 4 Web 应用程序项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11990036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:10:50  来源:igfitidea点击:

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

asp.net-mvcasp.net-mvc-4asp.net-web-apivisual-studio-2012

提问by aknuds1

I wish to add an ASP.NET Web APIto 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.

我希望将ASP.NET Web API添加到在 Visual Studio 2012 中开发的 ASP.NET MVC 4 Web 应用程序项目。我必须执行哪些步骤才能向项目添加正常运行的 Web API?我知道我需要一个从 ApiController 派生的控制器,但这就是我所知道的。

Let me know if I need to provide more details.

如果我需要提供更多详细信息,请告诉我。

回答by aknuds1

The steps I needed to perform were:

我需要执行的步骤是:

  1. Add reference to System.Web.Http.WebHost.
  2. Add App_Start\WebApiConfig.cs(see code snippet below).
  3. Import namespace System.Web.Httpin Global.asax.cs.
  4. Call WebApiConfig.Register(GlobalConfiguration.Configuration)in MvcApplication.Application_Start()(in file Global.asax.cs), beforeregistering the default Web Application route as that would otherwise take precedence.
  5. Add a controller deriving from System.Web.Http.ApiController.
  1. 添加对System.Web.Http.WebHost.
  2. 添加App_Start\WebApiConfig.cs(参见下面的代码片段)。
  3. 导入命名空间System.Web.HttpGlobal.asax.cs
  4. 注册默认 Web 应用程序路由之前(在文件中)调用WebApiConfig.Register(GlobalConfiguration.Configuration),否则将优先。MvcApplication.Application_Start()Global.asax.cs
  5. 添加一个从System.Web.Http.ApiController.

I could then learn enough from the tutorial(Your First ASP.NET Web API) to define my API controller.

然后我可以从教程(你的第一个 ASP.NET Web API)中学到足够的知识来定义我的 API 控制器。

App_Start\WebApiConfig.cs:

App_Start\WebApiConfig.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:

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:

2015 年 16 月 10 日更新:

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

Word 有它,必须安装 NuGet 包 Microsoft.AspNet.WebApi 才能正常工作。

回答by cdeutsch

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

2013 年 11 月 22 日更新 - 这是最新的 WebApi 包:

Install-Package Microsoft.AspNet.WebApi

Original answer (this is an older WebApi package)

原始答案(这是一个较旧的 WebApi 包)

Install-Package AspNetWebApi

More details.

更多详情

回答by kheya

To add WebAPI in my MVC 5 project.

在我的 MVC 5 项目中添加 WebAPI。

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Netand System.Net.Httpdlls if not there already

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

  4. Web.config will be modified accordingly by VS

  5. Add Application_Startmethod if not there already

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. 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 }
             );
         }
     }
    
  7. 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();
            }
        }
    }
    
  8. Rebuild and test

  9. 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>
    
  1. 打开 NuGet 包管理器控制台并运行

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. 添加对System.Web.Routing,System.Web.NetSystem.Net.Httpdll 的引用(如果尚未存在)

  3. 右键单击控制器文件夹 > 添加新项目 > Web > 添加 Web API 控制器

  4. Web.config 将被 VS 相应地修改

  5. Application_Start如果还没有添加方法

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  6. 添加以下类(我在 global.asax.cs 文件中添加)

    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 }
             );
         }
     }
    
  7. 相应地修改 web api 方法

    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();
            }
        }
    }
    
  8. 重建和测试

  9. 构建一个简单的html页面

    <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>
    

回答by Teoman shipahi

As soon as you add a "WebApi Controller" under controllers folder, Visual Studio takes care of dependencies automatically;

只要在控制器文件夹下添加“WebApi 控制器”,Visual Studio 就会自动处理依赖项;

Visual Studio has added the full set of dependencies for ASP.NET Web API 2 to project 'MyTestProject'.

The Global.asax.cs file in the project may require additional changes to enable ASP.NET Web API.

  1. Add the following namespace references:

    using System.Web.Http; using System.Web.Routing;

  2. If the code does not already define an Application_Start method, add the following method:

    protected void Application_Start() { }

  3. Add the following lines to the beginning of the Application_Start method:

    GlobalConfiguration.Configure(WebApiConfig.Register);

Visual Studio 已将 ASP.NET Web API 2 的全套依赖项添加到项目“MyTestProject”。

项目中的 Global.asax.cs 文件可能需要进行其他更改才能启用 ASP.NET Web API。

  1. 添加以下命名空间引用:

    使用 System.Web.Http; 使用 System.Web.Routing;

  2. 如果代码尚未定义 Application_Start 方法,请添加以下方法:

    protected void Application_Start() { }

  3. 将以下行添加到 Application_Start 方法的开头:

    GlobalConfiguration.Configure(WebApiConfig.Register);

回答by cuongle

You can install from nuget as the the below image:

您可以从 nuget 安装,如下图所示:

enter image description here

在此处输入图片说明

Or, run the below command line on Package Manager Console:

或者,在包管理器控制台上运行以下命令行:

Install-Package Microsoft.AspNet.WebApi

回答by Yarkov Anton

Before you start merging MVC and Web API projects I would suggest to read about cons and prosto separate these as different projects. One very important thing (my own) is authentication systems, which is totally different.

在您开始合并 MVC 和 Web API 项目之前,我建议您阅读有关利弊的信息,以将它们作为不同的项目分开。一件非常重要的事情(我自己的)是身份验证系统,它完全不同。

IF you need to use authenticated requests on both MVC and Web API, you need to remember that Web API is RESTful (don't need to keep session, simple HTTP requests, etc.), but MVC is not.

如果您需要在 MVC 和 Web API 上使用经过身份验证的请求,您需要记住 Web API 是 RESTful(不需要保持会话、简单的 HTTP 请求等),但 MVC 不是。

To look on the differences of implementations simply create 2 different projects in Visual Studio 2013 from Templates: one for MVC and one for Web API (don't forget to turn On "Individual Authentication" during creation). You will see a lot of difference in AuthencationControllers.

要查看实现的差异,只需在 Visual Studio 2013 中从模板创建 2 个不同的项目:一个用于 MVC,另一个用于 Web API(不要忘记在创建过程中打开“个人身份验证”)。您会在 AuthencationControllers 中看到很多不同之处。

So, be aware.

所以,请注意。

回答by Hakan F?st?k

NOTE : this is just an abbreviation of this answerabove

注意:这只是上述答案的缩写

  1. Open NuGet Package manager console and run

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. Add references to System.Web.Routing, System.Web.Netand System.Net.Httpdlls if not there already

  3. Add the following class

    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 }
             );
         }
     }
    
  4. Add Application_Startmethod if not there already (in global.asax.cs file)

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  5. Right click controllers folder > add new item > web > Add Web API controller

    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";
            }  
        }
    }
    
  1. 打开 NuGet 包管理器控制台并运行

    PM> Install-Package Microsoft.AspNet.WebApi
    
  2. 添加对System.Web.Routing,System.Web.NetSystem.Net.Httpdll 的引用(如果尚未存在)

  3. 添加以下类

    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 }
             );
         }
     }
    
  4. Application_Start如果还没有添加方法(在 global.asax.cs 文件中)

    protected void Application_Start()
    {
        //this should be line #1 in this method
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
    
  5. 右键单击控制器文件夹 > 添加新项目 > Web > 添加 Web API 控制器

    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";
            }  
        }
    }
    

回答by Sankar Krishnamoorthy

The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below

上述解决方案完美运行。我更喜欢在选择项目模板时选择 Web API 选项,如下图所示

Note:The solution works with Visual Studio 2013 or higher. The original question was asked in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.

注意:该解决方案适用于 Visual Studio 2013 或更高版本。最初的问题是在 2012 年提出的,现在是 2016 年,因此添加了 Visual Studio 2013 或更高版本的解决方案。

Project template showing web API option

显示 Web API 选项的项目模板

回答by iDeveloper

I had same problem, the solution was so easy

我有同样的问题,解决方案很简单

Right click on solotion install Microsoft.ASP.NET.WebApi from "Manage Nuget Package for Sulotion"

右键单击 solotion install Microsoft.ASP.NET.WebApi 从“Manage Nuget Package for Sulotion”

boom that's it ;)

繁荣就是这样;)