Skip to content

Commit

Permalink
Merge pull request #5 from ardalis/master
Browse files Browse the repository at this point in the history
Migrating from ASP.NET MVC5 to MVC6, Part 1
  • Loading branch information
ardalis committed Apr 6, 2015
2 parents 27782d1 + 5753332 commit c4320a9
Show file tree
Hide file tree
Showing 21 changed files with 508 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/_authors/steve-smith.rst
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
:orphan:
.. :orphan:
.. _Author:

Expand Down
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ ASP.NET MVC 6
:maxdepth: 1

migrating/migratingfrommvc5/migratingfrommvc5
migrating/migratingconfig/migratingconfig

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

.. _`Steve Smith`: Author_

In the previous article we `migrated configuration from an ASP.NET MVC 5 project to MVC 6 </migrating/migratingconfig/migratingconfig>`_. In this article, we migrate the registration, login, and user management features.

This article covers the following topics:
- Configure Identity and Membership
- Migrate Registration and Login Logic
- Migrate User Management Features

You can download the finished source from the project created in this article HERE **(TODO)**.

Configure Identity and Membership
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In ASP.NET MVC 5, authentication and identity features are configured in Startup.Auth.cs and IdentityConfig.cs, located in the App_Start folder. In MVC 6, these features are configured in Startup.cs. Before pulling in the required services and configuring them, we should add the required dependencies to the project. Open project.json and add "Microsoft.AspNet.Identity.EntityFramework" and "Microsoft.AspNet.Identity.Cookies" to the list of dependencies:

.. code-block:: javascript
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta3",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta3",
"Microsoft.AspNet.Security.Cookies": "1.0.0-beta3"
},
Now, open Startup.cs and update the ConfigureServices() method to use Entity Framework and Identity services:

.. code-block:: c#
public void ConfigureServices(IServiceCollection services)
{
// Add EF services to the services container.
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>();
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(Configuration)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc();
}
At this point, there are two types referenced in the above code that we haven't yet migrated from the MVC 5 project: ApplicationDbContext and ApplicationUser. Create a new Models folder in the MVC 6 project, and add two classes to it corresponding to these types. You will find the MVC 5 versions of these classes in /Models/IdentityModels.cs, but we will use one file per class in the migrated project since that's more clear.

ApplicationUser.cs:

.. code-block:: c#
using Microsoft.AspNet.Identity;
namespace NewMvc6Project.Models
{
public class ApplicationUser : IdentityUser
{
}
}
ApplicationDbContext.cs:

.. code-block:: c#
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
namespace NewMvc6Project.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
private static bool _created = false;
public ApplicationDbContext()
{
// Create the database and schema if it doesn't exist
// This is a temporary workaround to create database until Entity Framework database migrations
// are supported in ASP.NET 5
if (!_created)
{
Database.AsMigrationsEnabled().ApplyMigrations();
_created = true;
}
}
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer();
}
}
}
The MVC 5 Starter Web project doesn't include much customization of users, or the ApplicationDbContext. When migrating a real application, you will also need to migrate all of the custom properties and methods of your application's user and DbContext classes, as well as any other Model classes your application utilizes (for example, if your DbContext has a DbSet<Album>, you will of course need to migrate the Album class).

With these files in place, the Startup.cs file can be made to compile by updating its using statements:

.. code-block:: c#
using Microsoft.Framework.ConfigurationModel;
using Microsoft.AspNet.Hosting;
using NewMvc6Project.Models;
using Microsoft.AspNet.Identity;
Our application is now ready to support authentication and identity services - it just needs to have these features exposed to users.

Migrate Registration and Login Logic
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

With identity services configured for the application and data access configured using Entity Framework and SQL Server, we are now ready to add support for registration and login to the application. Recall that `earlier in the migration process </migrating/migratingfrommvc5/migratingfrommvc5.html#migrate-basic-controllers-views-and-static-content>`_ we commented out a reference to _LoginPartial in _Layout.cshtml. Now it's time to return to that code, uncomment it, and add in the necessary controllers and views to support login functionality.

Update _Layout.cshtml; uncomment the @Html.Partial line:

.. code-block:: c#
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
@*@Html.Partial("_LoginPartial")*@
</div>
</div>
Now, add a new MVC View Page called _LoginPartial to the Views/Shared folder:

.. image /static/AddLoginPartial.png
Update _LoginPartial.cshtml with the following code (replace all of its contents):

.. code-block:: c#
@using System.Security.Principal

@if (User.Identity.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}

At this point, you should be able to refresh the site in your browser.



Summary
^^^^^^^

ASP.NET 5 and MVC 6 introduce changes to the ASP.NET Identity 2 features that shipped with ASP.NET MVC 5. In this article, you have seen how to migrate the authentication and user management features of an ASP.NET MVC 5 project to MVC 6.

.. include:: /_authors/steve-smith.rst
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
84 changes: 84 additions & 0 deletions docs/migrating/migratingconfig/migratingconfig.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
Migrating Configuration From ASP.NET MVC 5 to MVC 6
===================================================
By `Steve Smith`_ | Originally Published: 1 June 2015

.. _`Steve Smith`: Author_

In the previous article we began `migrating an ASP.NET MVC 5 project to MVC 6 </migrating/migratingfrommvc5/migratingfrommvc5>`_. In this article, we migrate the configuration feature from ASP.NET MVC 5 to ASP.NET MVC 6.

This article covers the following topics:
- Set up Configuration
- Migrate Configuration Settings from web.config

You can download the finished source from the project created in this article HERE **(TODO)**.

Set up Configuration
^^^^^^^^^^^^^^^^^^^^

ASP.NET 5 and ASP.NET MVC 6 no longer use the Global.asax and Web.config files that previous versions of ASP.NET utilized. In earlier versions of ASP.NET, application startup logic was placed in an Application_StartUp() method within Global.asax. Later, in ASP.NET MVC 5, a Startup.cs file was included in the root of the project, and was called using an OwinStartupAttribute when the application started. ASP.NET 5 (and ASP.NET MVC 6) have adopted this approach completely, placing all startup logic in the Startup.cs file.

The web.config file has also been replaced in ASP.NET 5. Configuration itself can now be configured, as part of the application startup procedure described in Startup.cs. Configuration can still utilize XML files, if desired, but typically ASP.NET 5 projects will place configuration values in a JSON-formatted file, such as config.json. ASP.NET 5's configuration system can also easily access environment variables, which can provide a more secure and robust location for environment-specific values. This is especially true for secrets like connection strings and API keys that should not be checked into source control.

For this article, we are starting with the partially-migrated ASP.NET MVC 6 project from `the previous article <migratingfrommvc5>`_. To configure Configuration using the default MVC 6 settings, add the following constructor to the Startup.cs class in the root of the project:

.. code-block:: c#
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
Note that at this point the Startup.cs file will not compile, as we still need to add some using statements and pull in some dependencies. Add the following two using statements:

.. code-block:: c#
using Microsoft.Framework.ConfigurationModel;
using Microsoft.AspNet.Hosting;
Next, open project.json and add the Microsoft.Framework.ConfigurationModel.Json dependency:

.. code-block:: javascript
{
"webroot": "wwwroot",
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta3"
},
...
}
Finally, add a config.json file to the root of the project.

.. image:: _static/add-config-json.png

Migrate Configuration Settings from Web.config
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Our ASP.NET MVC 5 project included the required database connection string in Web.config, in the <connectionStrings> element. In our MVC 6 project, we are going to store this information in the config.json file. Open Config.json, and you should see that it already includes the following:

.. code-block:: javascript
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
}
}
}
Change the name of the Database from _CHANGE_ME. In the case of this migration, we are going to point to a new database, which we'll name NewMvc6Project to match our migrated project name.

Summary
^^^^^^^

ASP.NET 5 places all Startup logic for the application in a single file in which necessary services and dependencies can be defined and configured. It replaces the web.config file with a flexible configuration feature that can leverage a variety of file formats, such as JSON, as well as environment variables.

.. include:: /_authors/steve-smith.rst
Binary file not shown.
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.
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.
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.
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.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit c4320a9

Please sign in to comment.