如何对Web API添加到现有的ASP.NET MVC(5)Web应用程序项目? [英] How to add Web API to an existing ASP.NET MVC (5) Web Application project?

查看:754
本文介绍了如何对Web API添加到现有的ASP.NET MVC(5)Web应用程序项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你忘了剔网络API复选框(它添加到项目)进行新的MVC时(5)项目,你有什么需要做的添加Web API,并得到它的工作?

Assuming you forgot to tick the Web API checkbox (add it to the project) when making a new MVC (5) project, what do you need to do add Web API and get it working?

还有一堆的迁移问题,但没有一个似乎对添加Web API来一个MVC 5项目的完整和最新步骤,它似乎已经从一些老的回答改变。

<一个href=\"http://stackoverflow.com/questions/11990036/how-to-add-web-api-to-an-existing-asp-net-mvc-4-web-application-project\">Add网络API来MVC 4

<一个href=\"http://stackoverflow.com/questions/20226715/globalconfiguration-configure-not-$p$psent-after-web-api-2-and-net-4-5-1-migra\">Adding GlobalConfiguration.Configure(WebApiConfig.Register)MVC 4

推荐答案

使用的NuGet ,以获得最新的Web API。

Update the MVC project

Use Nuget to get the newest Web API.

项目 - 右键 - 管理的NuGet包 - 搜索Web API(微软的ASP.NET Web API ...),并把它安装到你的MVC项目

Project - Right click - Manage Nuget Packages - Search for Web API (Microsoft ASP.NET Web API ...) and install it to your MVC project.

那么你仍然需要获得网络API路由工作。
微软的配置的ASP.NET Web API 2

Then you still need to get Web API routing to work. From Microsoft's Configuring ASP.NET Web API 2

添加WebApiConfig.cs到App_Start /文件夹

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // TODO: Add any additional configuration code.

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        // WebAPI when dealing with JSON & JavaScript!
        // Setup json serialization to serialize classes to camel (std. Json format)
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

        }
    }
}

如果你有一个MVC项目将有的Global.asax.cs ,添加新的路线。 <一href=\"http://stackoverflow.com/questions/22401403/add-web-api-to-an-existing-mvc-5-web-application\">Order在Global.asax.cs中的路线是至关重要的。注意有哪些使用过时的例子
WebApiConfig.Register

If you have an MVC Project it will have Global.asax.cs, add the new routes. Order of the Global.asax.cs routes is critical. Note there are outdated examples which use WebApiConfig.Register

这行添加到的Global.asax.cs:
GlobalConfiguration.Configure(WebApiConfig.Register);

        // Default stuff
        AreaRegistration.RegisterAllAreas();

        // Manually installed WebAPI 2.2 after making an MVC project.
        GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
        //WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED

        // Default stuff
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

的WebAPI帮助

要获得(非常)的有用的WebAPI帮助页面中,安装WebAPI.HelpPage。
见<一href=\"http://channel9.msdn.com/Events/Build/2014/3-644\">http://channel9.msdn.com/Events/Build/2014/3-644 (〜42分钟)它做什么。它看起来非常有帮助!

WebAPI Help

To get the (very) helpful WebAPI help pages, install WebAPI.HelpPage. See http://channel9.msdn.com/Events/Build/2014/3-644 (~42 minutes in) for what it does. It looks very helpful!

的NuGet控制台:安装封装Microsoft.AspNet.WebApi.HelpPage

Nuget Console: Install-Package Microsoft.AspNet.WebApi.HelpPage

要控制器文件夹 - >添加新项目 - >网络API控制器类

To the controllers folder -> Add new item -> Web API Controller Class.

public class TestController : ApiController
{
    //public TestController() { }

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
    //...
}

现在,你可以在IE / FF / Chrome的测试和往常一样,还是在JavaScript的控制台非得到测试。

Now you can test in IE/FF/Chrome as usual, or in the JavaScript consoles for non-get testing.

(只需在URL中的控制器,它会调用在新的Web API控制器的GET()动作,它会自动映射到视REST方法/措施如PUT / POST / GET / DELETE。你不需要通过动作就像在MVC给他们打电话)
直接的网址:

(With just the controller in the URL it will call the GET() action in the new Web API Controller, it's automatically mapped to methods/actions depending on the REST e.g. PUT/POST/GET/DELETE. You don't need to call them by action like in MVC) The URL directly:

http://localhost:PORT/api/CONTROLLERNAME/

或者使用jQuery查询控制器。
运行该项目,打开控制台(F12在IE浏览器),并尝试运行的Ajax查询。 (检查连接端口和放大器; CONTROLLERNAME)

Alternatively use jQuery to query the controller. Run the project, Open the console (F12 in IE) and try run an Ajax query. (Check your PORT & CONTROLLERNAME)

$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
    //$( ".result" ).html( data );
    alert( "Get data received:" + data);
});

边注:有一些优点/缺点组合时需要考虑在项目 MVC和Web API

Side note: There are some pros/cons to consider when combining MVC and Web API in a project

的WebAPI帮助验证:
的http://本地主机:PORT /帮助

这篇关于如何对Web API添加到现有的ASP.NET MVC(5)Web应用程序项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆