diff --git a/docs/index.rst b/docs/index.rst index e2aa83bca4e6..61630f146ab0 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -29,7 +29,7 @@ Web API .. toctree:: :maxdepth: 1 - + webapi/migratingfromwebapi2/migratingfromwebapi2 Mobile ------ diff --git a/docs/webapi/migratingfromwebapi2/_static/add-web-project.png b/docs/webapi/migratingfromwebapi2/_static/add-web-project.png new file mode 100644 index 000000000000..bd2c2ffc4817 Binary files /dev/null and b/docs/webapi/migratingfromwebapi2/_static/add-web-project.png differ diff --git a/docs/webapi/migratingfromwebapi2/_static/aspnet-5-webapi.png b/docs/webapi/migratingfromwebapi2/_static/aspnet-5-webapi.png new file mode 100644 index 000000000000..7dd74fe1ab96 Binary files /dev/null and b/docs/webapi/migratingfromwebapi2/_static/aspnet-5-webapi.png differ diff --git a/docs/webapi/migratingfromwebapi2/_static/webapimigration-solution.png b/docs/webapi/migratingfromwebapi2/_static/webapimigration-solution.png new file mode 100644 index 000000000000..3e76b9124d10 Binary files /dev/null and b/docs/webapi/migratingfromwebapi2/_static/webapimigration-solution.png differ diff --git a/docs/webapi/migratingfromwebapi2/migratingfromwebapi2.rst b/docs/webapi/migratingfromwebapi2/migratingfromwebapi2.rst new file mode 100644 index 000000000000..043134e3b966 --- /dev/null +++ b/docs/webapi/migratingfromwebapi2/migratingfromwebapi2.rst @@ -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 `_. + +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#) `_ 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 `_, 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 `). 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]")] + +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 `_ + +.. include:: /_authors/steve-smith.rst diff --git a/docs/yourfirst/fundamentalconcepts/fundamentalconcepts.rst b/docs/yourfirst/fundamentalconcepts/fundamentalconcepts.rst index 9d4ae7f8c7fb..c801f3bd48ff 100644 --- a/docs/yourfirst/fundamentalconcepts/fundamentalconcepts.rst +++ b/docs/yourfirst/fundamentalconcepts/fundamentalconcepts.rst @@ -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 ^^^^^^^^^^^^^^^^^^^ diff --git a/samples/WebAPIMigration/ProductsApp/App_Start/WebApiConfig.cs b/samples/WebAPIMigration/ProductsApp/App_Start/WebApiConfig.cs new file mode 100644 index 000000000000..fce089f9b25a --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/App_Start/WebApiConfig.cs @@ -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 } + ); + } + } +} diff --git a/samples/WebAPIMigration/ProductsApp/Controllers/ProductsController.cs b/samples/WebAPIMigration/ProductsApp/Controllers/ProductsController.cs new file mode 100644 index 000000000000..a969883d1da2 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Controllers/ProductsController.cs @@ -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 GetAllProducts() + { + return products; + } + + public IHttpActionResult GetProduct(int id) + { + var product = products.FirstOrDefault((p) => p.Id == id); + if (product == null) + { + return NotFound(); + } + return Ok(product); + } + } +} diff --git a/samples/WebAPIMigration/ProductsApp/Global.asax b/samples/WebAPIMigration/ProductsApp/Global.asax new file mode 100644 index 000000000000..4209ae8e8344 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="ProductsApp.WebApiApplication" Language="C#" %> diff --git a/samples/WebAPIMigration/ProductsApp/Global.asax.cs b/samples/WebAPIMigration/ProductsApp/Global.asax.cs new file mode 100644 index 000000000000..55b834904268 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Global.asax.cs @@ -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); + } + } +} diff --git a/samples/WebAPIMigration/ProductsApp/Models/Product.cs b/samples/WebAPIMigration/ProductsApp/Models/Product.cs new file mode 100644 index 000000000000..bd08186a50b3 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Models/Product.cs @@ -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; } + } +} \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsApp/ProductsApp.csproj b/samples/WebAPIMigration/ProductsApp/ProductsApp.csproj new file mode 100644 index 000000000000..034246b0b891 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/ProductsApp.csproj @@ -0,0 +1,137 @@ + + + + + Debug + AnyCPU + + + 2.0 + {8811BC19-201C-4487-A264-C6704D245010} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + ProductsApp + ProductsApp + v4.5 + true + + + + + ..\ + true + + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + + ..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll + True + + + + ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll + True + + + + + + + + + + + + ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll + True + + + ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll + True + + + + + + + + + + + + + + + + + + Global.asax + + + + + + + + Web.config + + + Web.config + + + + + + + 10.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + True + True + 47503 + / + http://localhost:47503/ + False + False + + + False + + + + + + + \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsApp/Properties/AssemblyInfo.cs b/samples/WebAPIMigration/ProductsApp/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..fcc92df368fe --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ProductsApp")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ProductsApp")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("15c57bd4-a2eb-48c8-89bb-acd56faa7d28")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/samples/WebAPIMigration/ProductsApp/Web.Debug.config b/samples/WebAPIMigration/ProductsApp/Web.Debug.config new file mode 100644 index 000000000000..2e302f9f9548 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Web.Debug.config @@ -0,0 +1,30 @@ + + + + + + + + + + \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsApp/Web.Release.config b/samples/WebAPIMigration/ProductsApp/Web.Release.config new file mode 100644 index 000000000000..c35844462ba8 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Web.Release.config @@ -0,0 +1,31 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsApp/Web.config b/samples/WebAPIMigration/ProductsApp/Web.config new file mode 100644 index 000000000000..3063931e0364 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/Web.config @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/WebAPIMigration/ProductsApp/packages.config b/samples/WebAPIMigration/ProductsApp/packages.config new file mode 100644 index 000000000000..07a69e35f911 --- /dev/null +++ b/samples/WebAPIMigration/ProductsApp/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsDnx/Controllers/ProductsController.cs b/samples/WebAPIMigration/ProductsDnx/Controllers/ProductsController.cs new file mode 100644 index 000000000000..e71c950bf92f --- /dev/null +++ b/samples/WebAPIMigration/ProductsDnx/Controllers/ProductsController.cs @@ -0,0 +1,37 @@ +using Microsoft.AspNet.Mvc; +using ProductsDnx.Models; +using System.Collections.Generic; +using System.Linq; + +namespace ProductsDnx.Controllers +{ + [Route("api/[controller]")] + public class ProductsController : Controller + { + 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 } + }; + + // /api/products + [HttpGet] + public IEnumerable GetAllProducts() + { + return products; + } + + // /api/products/1 + [HttpGet("{id}")] + public IActionResult GetProduct(int id) + { + var product = products.FirstOrDefault((p) => p.Id == id); + if (product == null) + { + return HttpNotFound(); + } + return new ObjectResult(product); + } + } +} diff --git a/samples/WebAPIMigration/ProductsDnx/Models/Product.cs b/samples/WebAPIMigration/ProductsDnx/Models/Product.cs new file mode 100644 index 000000000000..3b13c07d2da6 --- /dev/null +++ b/samples/WebAPIMigration/ProductsDnx/Models/Product.cs @@ -0,0 +1,11 @@ + +namespace ProductsDnx.Models +{ + public class Product + { + public int Id { get; set; } + public string Name { get; set; } + public string Category { get; set; } + public decimal Price { get; set; } + } +} \ No newline at end of file diff --git a/samples/WebAPIMigration/ProductsDnx/Project_Readme.html b/samples/WebAPIMigration/ProductsDnx/Project_Readme.html deleted file mode 100644 index b693be4eba03..000000000000 --- a/samples/WebAPIMigration/ProductsDnx/Project_Readme.html +++ /dev/null @@ -1,204 +0,0 @@ - - - - - Welcome to ASP.NET 5 - - - - - - - - - - \ No newline at end of file