visit
This is the second important characteristic that allows developers to integrate new features into their solution more flexible.Performance is another step towards building a high-performance application. ASP.NET Core handles 2.300% more requests per second than ASP.NET 4.6, and 800% more requests per second than node.js. You can check the detailed performance tests yourself or.
Middleware is a new light and fast modular pipeline for in-app requests. Each part of middleware processes an HTTP request, and then either decides to return the result or passes the next part of middleware.
Step 1. Preparing a toolkit
The first thing you need is to upgrade Visual Studio 2017 to version 15.3 or later and install the latest version of .NET Core SDK.Before porting, we advise to use . This can be a good starting point to understand how labor-intensive porting from one platform to another will be. Nevertheless, this tool does not cover all the issues, this process has many pitfalls to be solved as they emerge. Below we will describe the main steps and the solutions used in nopCommerce project.The first and the easiest thing to do is to update links to the libraries used in the project so to they support .NET Standard.
Step 2. NuGet package compatibility analysis to support .Net standard
If you use NuGet packages in your project, check whether they are compatible with .NET Core. One way to do this is to use the tool.Step 3. The new format of csproj file in .NET Core
A new approach for adding references to third-party packages was introduced in .NET Core. When adding a new class library, you need to open the main project file and replace its contents as follows:<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.6" />
...
</ItemGroup>
...
</Project>
For more information on comparing the project.json and CSPROJ properties, read the official documentation and
Step 4. Namespace update
Delete all uses of System.Web and replace them with Microsoft.AspNetCore.Step 5. Configure the Startup.cs file instead of using global.asax
ASP.NET Core has a new way of loading the app. The app entry point is
Startup
, and there is no dependency on the Global.asax file. Startup
registers the middlewares in the app. Startup
must include the Configure
method. The required middleware should be added to the pipeline in Configure
.Issues to solve in Startup.cs:
//add basic MVC feature
var mvcBuilder = services.AddMvc();
//add custom model binder provider (to the top of the provider list)
mvcBuilder.AddMvcOptions(options => options.ModelBinderProviders.Insert(0, new NopModelBinderProvider()));
/// <summary>
/// Represents model binder provider for the creating NopModelBinder
/// </summary>
public class NopModelBinderProvider : IModelBinderProvider
{
/// <summary>
/// Creates a nop model binder based on passed context
/// </summary>
/// <param name="context">Model binder provider context</param>
/// <returns>Model binder</returns>
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
var modelType = context.Metadata.ModelType;
if (!typeof(BaseNopModel).IsAssignableFrom(modelType))
return null;
//use NopModelBinder as a ComplexTypeModelBinder for BaseNopModel
if (context.Metadata.IsComplexType && !context.Metadata.IsCollectionType)
{
//create binders for all model properties
var propertyBinders = context.Metadata.Properties
.ToDictionary(modelProperty => modelProperty, modelProperty => context.CreateBinder(modelProperty));
return new NopModelBinder(propertyBinders, EngineContext.Current.Resolve<ILoggerFactory>());
}
//or return null to further search for a suitable binder
return null;
}
}
app.UseMvc(routes => { routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
When doing it, the folder with the name Area with the Admin folder inside, should be in the app root. Now the attribute
[Area("Admin")] [Route("admin")].
will be used to connect the controller with this area.It remains only to create views for all the actions described in the controller.[Area("Admin")]
[Route("admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
Validation
IFormCollection should not be passed to the controllers since in this case, asp.net server validation is disabled - MVC is suppressing further validation if the IFormCollection is found to be not null. To solve the problem, this property might be added to the model, this will prevent us from passing directly to the controller method.This rule works only if a model is available, if there is no model, there will be no validation.Child properties are no longer automatically validated and should be specified manually.
Step 6. Migrate HTTP handlers and HttpModules to Middleware
HTTP handlers and HTTP modules are in fact very similar to the concept of, but unlike modules, the middleware order is based on the order in which they are inserted into the request pipeline. The order of modules is mainly based on the events of The order of middleware for responses is opposite to the order for requests, while the order of modules for requests and responses is the same. Knowing this, you can proceed with the update.What should be updated:
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(IAuthenticationSchemeProvider schemes, RequestDelegate next)
{
Schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
_next = next ?? throw new ArgumentNullException(nameof(next));
}
public IAuthenticationSchemeProvider Schemes { get; set; }
public async Task Invoke(HttpContext context)
{
context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature
{
OriginalPath = context.Request.Path,
OriginalPathBase = context.Request.PathBase
});
var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
try
{
if (await handlers.GetHandlerAsync(context, scheme.Name) is IAuthenticationRequestHandler handler && await handler.HandleRequestAsync())
return;
}
catch
{
// ignored
}
}
var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
if (result?.Principal != null)
{
context.User = result.Principal;
}
}
await _next(context);
}
}
public interface INopStartup
{
/// <summary>
/// Add and configure any of the middleware
/// </summary>
/// <param name="services">Collection of service descriptors</param>
/// <param name="configuration">Configuration of the application</param>
void ConfigureServices(IServiceCollection services, IConfiguration configuration);
/// <summary>
/// Configure the using of added middleware
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
void Configure(IApplicationBuilder application);
/// <summary>
/// Gets order of this startup configuration implementation
/// </summary>
int Order { get; }
}
/// <summary>
/// Represents object for the configuring authentication middleware on application startup
/// </summary>
public class AuthenticationStartup : INopStartup
{
/// <summary>
/// Add and configure any of the middleware
/// </summary>
/// <param name="services">Collection of service descriptors</param>
/// <param name="configuration">Configuration of the application</param>
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
//add data protection
services.AddNopDataProtection();
//add authentication
services.AddNopAuthentication();
}
/// <summary>
/// Configure the using of added middleware
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
public void Configure(IApplicationBuilder application)
{
//configure authentication
application.UseNopAuthentication();
}
/// <summary>
/// Gets order of this startup configuration implementation
/// </summary>
public int Order => 500; //authentication should be loaded before MVC
}
Step 7. Using built-in DI
injection is one of the key features when designing an app in ASP.NET Core. You can develop loosely coupled applications that are more testable, modular and as a result more maintainable. This was made possible by following the principle of dependency inversion. To inject dependencies, we used IoC (Inversion of Control) containers. In ASP.NET Core, such a container is represented by the IServiceProvider interface. Services are installed in the app in the Startup.ConfigureServices() method.Any registered service can be configured with three scopes:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddSingleton<Isingleton,MySingleton>();
Step 8. Using WebAPI project compatibility shells (Shim)
To simplify migration of an existing Web API, we advise using the NuGet package. It supports the following:
services.AddMvc().AddWebApiConventions();
routes.MapWebApiRoute(name: "DefaultApi",
template: "api/{controller}/{id?}"
);
Step 9. Porting Application Configuration
Some settings were previously saved in the web.config file. Now we use based on the key-value pairs set by configuration providers. This is the recommended method in ASP.NET Core, and we use the appsettings.json file.
You can also use the NuGet package
System.Configuration.ConfigurationManager
if for some reason you want to continue using *.config. In this case, the app cannot run on Unix platforms, but on IIS only.If you want to use the Azure key storage configuration provider, then you need to refer to. Our project did not contain such a task.Step 10. Porting static content to wwwroot
To serve , specify to web host the content root of the current directory. The default is wwwroot. You can configure your folder for storing static files by setting up middleware.Step 11. Porting EntityFramework to EF Core
If the project uses some specific, that are in EF Core, it makes sense to run the application on the NET Framework. Though in this case, we will have to reject the multi-platform feature, and the application will run on Windows and IIS only. Below are the main changes to be considered:
/// <summary>
/// Register base object context
/// </summary>
/// <param name="services">Collection of service descriptors</param>
public static void AddNopObjectContext(this IServiceCollection services)
{
services.AddDbContextPool<NopObjectContext>(optionsBuilder =>
{
optionsBuilder.UseSqlServerWithLazyLoading(services);
});
}
/// <summary>
/// SQL Server specific extension method for Microsoft.EntityFrameworkCore.DbContextOptionsBuilder
/// </summary>
/// <param name="optionsBuilder">Database context options builder</param>
/// <param name="services">Collection of service descriptors</param>
public static void UseSqlServerWithLazyLoading(this DbContextOptionsBuilder optionsBuilder, IServiceCollection services)
{
var nopConfig = services.BuildServiceProvider().GetRequiredService<NopConfig>();
var dataSettings = DataSettingsManager.LoadSettings();
if (!dataSettings?.IsValid ?? true)
return;
var dbContextOptionsBuilder = optionsBuilder.UseLazyLoadingProxies();
if (nopConfig.UseRowNumberForPaging)
dbContextOptionsBuilder.UseSqlServer(dataSettings.DataConnectionString, option => option.UseRowNumberForPaging());
else
dbContextOptionsBuilder.UseSqlServer(dataSettings.DataConnectionString);
}
Step 12. Removing all HttpContext references and replacing obsolete classes and changing the namespace
Step 13. Authentication and authorization update
As was already mentioned above, nopCommerce project does not involve the built-in authentication system, it is implemented in a separate middleware layer.However, ASP.NET Core has its own system for credentials providing. You can view the to know about them in details.
As for data protection, we no longer use . Instead, we use the built-in data protection feature. By default, keys are generated when the application starts. As the data storage can be:Step 14. JS/CSS update
The way of using static resources has changed, now they should all be stored in the root folder of the project wwwroot, unless other settings are made.
When using javascript built-in blocks, we recommend moving them to the end of the page. Just use the asp-location = "Footer" attribute for your <script> tags. The same rule applies to js files.Use the extension as a replacement for System.Web.Optimization - this will enable bundling and minification. JavaScript and CSS while building the project ().Step 15. Porting views
First of all, Child Actions are no longer used, instead, ASP.NET Core suggests using a new high-performance tool - called asynchronously.How to get a string from ViewComponent:
/// <summary>
/// Render component to string
/// </summary>
/// <param name="componentName">Component name</param>
/// <param name="arguments">Arguments</param>
/// <returns>Result</returns>
protected virtual string RenderViewComponentToString(string componentName, object arguments = null)
{
if (string.IsNullOrEmpty(componentName))
throw new ArgumentNullException(nameof(componentName));
var actionContextAccessor = HttpContext.RequestServices.GetService(typeof(IActionContextAccessor)) as IActionContextAccessor;
if (actionContextAccessor == null)
throw new Exception("IActionContextAccessor cannot be resolved");
var context = actionContextAccessor.ActionContext;
var viewComponentResult = ViewComponent(componentName, arguments);
var viewData = ViewData;
if (viewData == null)
{
throw new NotImplementedException();
}
var tempData = TempData;
if (tempData == null)
{
throw new NotImplementedException();
}
using (var writer = new StringWriter())
{
var viewContext = new ViewContext(
context,
NullView.Instance,
viewData,
tempData,
writer,
new HtmlHelperOptions());
// IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
var viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService<IViewComponentHelper>();
(viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);
var result = viewComponentResult.ViewComponentType == null ?
viewComponentHelper.InvokeAsync(viewComponentResult.ViewComponentName, viewComponentResult.Arguments):
viewComponentHelper.InvokeAsync(viewComponentResult.ViewComponentType, viewComponentResult.Arguments);
result.Result.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
This makes application development a whole lot easier. And of course, you can implement your own tag helpers.We started using dependency injection in views instead of enabling settings and services using EngineContext.So, the main points on porting views are as follows:
Being first is not easy, but we are sure we’ve made the right choice, and our huge community supported us in this.We were able to fully adapt our project after the release of .NET Core 2.1, having by that time a stable solution already working on the new architecture. It remained only to replace some packages and rewrite the work with EF Core. Thus, it took us several months and two released versions to completely migrate to the new framework. We can say with confidence that we are the to carry out such a migration. In this guide, we tried to put together the entire migration process in a structured form and describe various bottlenecks so that other developers could rely on this material and follow the roadmap when solving the same task.