首页 文章

如何将Web API添加到现有的ASP.NET MVC(5)Web应用程序项目?

提问于
浏览
131

假设您在创建新的MVC(5)项目时忘记勾选Web API复选框(将其添加到项目中),您需要做什么才能添加Web API并使其正常工作?

有一堆迁移问题,但似乎都没有将Web API添加到MVC 5项目的完整和最新步骤,而且似乎已经从一些旧的答案中改变了 .

Add Web API to MVC 4

Adding GlobalConfiguration.Configure(WebApiConfig.Register) MVC 4

1 回答

  • 234

    更新MVC项目

    使用 Nuget 获取最新的Web API .

    项目 - 右键单击 - 管理Nuget包 - 搜索Web API(Microsoft ASP.NET Web API ...)并将其安装到您的MVC项目中 .

    然后你仍然需要让 Web API routing 工作 . 来自Microsoft's Configuring ASP.NET Web API 2

    将WebApiConfig.cs添加到App_Start /文件夹

    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 ,添加新路由 . Order of the Global.asax.cs routes is critical.注意有过时的例子使用 WebApiConfig.Register

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

    protected void Application_Start()
    {
        // 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帮助

    要获取( veryhelpful WebAPI help pages,请安装WebAPI.HelpPage . 请参阅http://channel9.msdn.com/Events/Build/2014/3-644(约42分钟) . 它看起来非常有用!

    Nuget控制台: Install-Package Microsoft.AspNet.WebApi.HelpPage

    验证WebAPI是否正常工作:

    到controllers文件夹 - >添加新项 - > 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控制台中进行非测试测试 .

    (只有URL中的控制器将调用新Web API控制器中的GET()操作,它会根据REST自动映射到方法/操作,例如PUT / POST / GET / DELETE . 您无需调用他们通过像MVC一样的动作)URL直接:

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

    Alternatively 使用jQuery查询控制器 . 运行项目,打开控制台(IE中的F12)并尝试运行Ajax查询 . (检查您的PORT&CONTROLLERNAME)

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

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

    WebAPI Help verification: http://localhost:PORT/help

相关问题