Converting Razor (& Swift) Templates
How to migrate Razor templates (.cshtml files) from AspNet to AspNetCore
There are two key differences between DW9 and DW10 templates due to the technology upgrade:
- @Helpers are out, as .NET Core does not support them. You must convert your helpers to functions instead.
- You can no longer use System.Web – which includes HttpContext. Instead you can use Dynamicweb.Context
DynamicWeb 10 features a new razor template parser. Though it is syntactically compatible with the one in DW9 parsing issues may occur. You will need to test your templates thoroughly and not just assume that they behave identically to DW9
To help you migrate your templates, we've built a Template Compatibility debug-tool which auto-converts DW9 templates to DW10 format runtime, saves them, and uses the converted templates if detected. Please only use this in preparation for a full migration of a design and on a development or staging environment, not in production.
Examples
A simple @GetText()
method is used the same way in razor templates on both .NET4 and .NET Core, e.g.:
<div>@GetText()</div>
but the underlying implementation differs greatly:
#.NET4 Razor Helper
@helper GetText()
{
if(Model.ID > 0)
{
<h2>Page id: @Model.ID </h2>
}
}
#.NET Core Razor method
@functions
{
void GetText()
{
(if Model.ID > 0)
{
<h2>Page id: @Model.ID </h2>
}
}
}
Similarly use of system.web has not survived so in order to get a querystring parameter from context in .NET4 you would do something akin to:
@using System.Web
@{
var id = HttpContext.Current.Request.QueryString("ID")
}
in .NET Core you need to get the context from Dynamicweb
@{
var id = Dynamicweb.Context.Current.Request.QueryString("ID")
}