Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Web API
.. toctree::
:maxdepth: 1


webapi/migratingfromwebapi2/migratingfromwebapi2

Mobile
------
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
146 changes: 146 additions & 0 deletions docs/webapi/migratingfromwebapi2/migratingfromwebapi2.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
Migrating From ASP.NET Web API 2 to MVC 6
=========================================
By `Steve Smith`_ | Originally Published: 1 June 2015

.. _`Steve Smith`: Author_

ASP.NET Web API 2 was separate from ASP.NET MVC 5, with each using their own libraries for dependency resolution, among other things. In MVC 6, Web API has been merged with MVC, providing a single, consistent way of building web applications. In this article we demonstrate the steps required to migrate from an ASP.NET Web API 2 project to MVC 6.

This article covers the following topics:
- Review Web API 2 Project
- Create the Destination Project
- Migrate Configuration
- Migrate Models and Controllers

You can view the finished source from the project created in this article `on GitHub <https://github.com/aspnet/Docs/tree/master/samples/WebAPIMigration>`_.

Review Web API 2 Project
^^^^^^^^^^^^^^^^^^^^^^^^

This article uses the sample project, ProductsApp, created in the article, `Getting Started with ASP.NET Web API 2 (C#) <http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api>`_ as its starting point. In that project, a simple Web API 2 project is configured as follows.

In Global.asax.cs, a call is made to WebApiConfig.Register:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsApp/global.asax.cs
:language: c#
:emphasize-lines: 14
:linenos:

WebApiConfig is defined in App_Start, and has just one static Register method:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsApp/App_Start/WebApiConfig.cs
:language: c#
:emphasize-lines: 15-20
:linenos:

This class configures `attribute routing <http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2>`_, although it's not actually being used in the project, as well as the routing table that Web API 2 uses. In this case, Web API will expect URLs to match the format */api/{controller}/{id}*, with *{id}* being optional.

The ProductsApp project includes just one simple controller, which inherits from ApiController and exposes two methods:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsApp/Controllers/ProductsController.cs
:language: c#
:emphasize-lines: 19,24
:linenos:

Finally, the model, Product, used by the ProductsApp, is a simple class:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsApp/Models/Product.cs
:language: c#
:linenos:

Now that we have a simple project from which to start, we can demonstrate how to migrate this Web API 2 project to ASP.NET MVC 6.

Create the Destination Project
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Using Visual Studio 2015, create a new, empty solution, and add the existing ProductsApp project to it. Then, add a new Web Project to the solution. Name the new project 'ProductsDnx'.

.. image:: _static/add-web-project.png

Next, choose the ASP.NET 5 Web API template project. We will migrate the ProductsApp contents to this new project.

.. image:: _static/aspnet-5-webapi.png

Delete the Project_Readme.html file from the new project. Your solution should now look like this:

.. image:: _static/webapimigration-solution.png

.. migrate-webapi-config:

Migrate Configuration
^^^^^^^^^^^^^^^^^^^^^

ASP.NET 5 no longer uses global.asax, web.config, or App_Start folders. Instead, all startup tasks are done in Startup.cs in the root of the project, and static configuration files can be wired up from there if needed (Learn more about :ref:`ASP.NET 5 Application Startup <fundamentalconcepts-application-startup>`). Since Web API is now built into MVC 6, there is less need to configure it. Attribute-based routing is now included by default when UseMvc() is called, and this is the recommended approach for configuring Web API routes (and is how the Web API starter project handles routing).

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsDnx/Startup.cs
:language: c#
:emphasize-lines: 27
:linenos:

Assuming you want to use attribute routing in your project going forward, you don't need to do any additional configuration. You can simply apply the attributes as needed to your controllers and actions,, as is done in the sample ValuesController.cs class that is included in the Web API starter project:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsDnx/Controllers/ValuesController.cs
:language: c#
:emphasize-lines: 8,12,19,32,38
:linenos:

Note the presence of *[controller]* on line 8. Attribute-based routing now supports certain tokens, such as *[controller]* and *[action]* that are replaced at runtime with the name of the controller or action to which the attribute has been applied. This serves to reduce the number of magic strings in the project, and ensures the routes will be kept synchronized with their corresponding controllers and actions when automatic rename refactorings are applied.

To migrate the Products API controller, we must first copy ProductsController to the new project. Then simply include the route attribute on the controller:

.. code-block:: c#

[Route("api/[controller]")]
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The route token syntax (here used for inserting the controller name in the route) is new and is worth explaining or pointing to a more general routing document with more details

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In MVC 6 adding just the route on the controller class isn't enough. This would define a base route for each action, but you would still need to define routes on each action to disambiguate where the request should go. Otherwise you will just get ambiguous match errors. MVC 6 does not use the elaborate action selection logic from Web API 2 - each action in an MVC 6 based Web API really needs to have a route. See the default ValuesController in the Web API project template.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add some explanation; I agree we should probably dive more deeply into the new routing features and recommendations in a related article.


You also need to add the [HttpGet] attribute to the two methods, since they both should be called via HTTP Get. Include the expectation of an "id" parameter in the attribute for GetProduct():

.. code-block:: c#

// /api/products
[HttpGet]
...

// /api/products/1
[HttpGet("{id}")]

At this point routing is configured correctly, but we can't yet test it because there are changes we must make before ProductsController will compile.

Migrate Models and Controllers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The last step in the migration process for this simple Web API project is to copy over the Controllers and any Models they use. In this case, simply copy Controllers/ProductsController.cs from the original project to the new one. Then, copy the entire Models folder from the original project to the new one. Adjust the namespaces to match the new project name (`ProductsDnx`). At this point, you can build the application, and you will find a number of compilation errors. These should generally fall into three categories:

- `ApiController` does not exist
- `System.Web.Http` namespace does not exist
- `IHttpActionResult` does not exist
- `NotFound` does not exist
- `Ok` does not exist

Fortunately, these are all very easy to correct:

- Change `ApiController` to `Controller` (you may need to add `using Microsoft.AspNet.Mvc`)
- Delete any using statement referring to `System.Web.Http`
- Change any method returning `IHttpActionResult` to return a `IActionResult`
- Change `NotFound` to `HttpNotFound`
- Change `Ok(product)` to `new ObjectResult(product)`

Once these changes have been made and unused using statements removed, the migrated ProductsController class looks like this:

.. literalinclude:: ../../../samples/WebAPIMigration/ProductsDnx/Controllers/ProductsController.cs
:language: c#
:emphasize-lines: 1,2,6,8-9,27,32,34
:linenos:

You should now be able to run the migrated project and browse to /api/products, and you should see the full list of 3 products. Browse to /api/products/1 and you should see the first product.

Summary
^^^^^^^

Migrating a simple Web API 2 project to MVC 6 is fairly straightforward, thanks to the fact that Web API has been merged with MVC 6 in ASP.NET 5. The main pieces every Web API 2 project will need to migrate are routes, controllers, and models, along with updates to the types used by MVC 6 controllers and actions.

Related Resources
^^^^^^^^^^^^^^^^^

`Create a Web API in MVC 6 <http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6>`_

.. include:: /_authors/steve-smith.rst
1 change: 1 addition & 0 deletions docs/yourfirst/fundamentalconcepts/fundamentalconcepts.rst
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ Run the application and navigate to the About page and you should see the result
.. image:: _static/about-page.png

.. _Startup.cs:
.. _fundamentalconcepts-application-startup:

Application Startup
^^^^^^^^^^^^^^^^^^^
Expand Down
24 changes: 24 additions & 0 deletions samples/WebAPIMigration/ProductsApp/App_Start/WebApiConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ProductsApp
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace ProductsApp.Controllers
{
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};

public IEnumerable<Product> GetAllProducts()
{
return products;
}

public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
}
1 change: 1 addition & 0 deletions samples/WebAPIMigration/ProductsApp/Global.asax
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<%@ Application Codebehind="Global.asax.cs" Inherits="ProductsApp.WebApiApplication" Language="C#" %>
17 changes: 17 additions & 0 deletions samples/WebAPIMigration/ProductsApp/Global.asax.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Routing;

namespace ProductsApp
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
11 changes: 11 additions & 0 deletions samples/WebAPIMigration/ProductsApp/Models/Product.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

namespace ProductsApp.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
137 changes: 137 additions & 0 deletions samples/WebAPIMigration/ProductsApp/ProductsApp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{8811BC19-201C-4487-A264-C6704D245010}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ProductsApp</RootNamespace>
<AssemblyName>ProductsApp</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<UseGlobalApplicationHostFile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.ApplicationServices" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Configuration" />
<Reference Include="System.Web.Services" />
<Reference Include="System.EnterpriseServices" />
</ItemGroup>
<ItemGroup>
<Content Include="Global.asax" />
<Content Include="Web.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\ProductsController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Models\Product.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="packages.config" />
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
<None Include="Web.Release.config">
<DependentUpon>Web.config</DependentUpon>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>47503</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:47503/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
Loading