Starting with ASP.NET Core development
This page covers how to set up an environment for developing Xperience applications under ASP.NET Core. The process consists of the following main steps:
- Install a blank ASP.NET Core project.
- Set up a local hosting environment.
- Configure the project’s startup.
- (Optional) Enable additional Xperience features according to your requirements.
- (Optional) Configure the application’s preview mode.
- Start developing your site.
Installing ASP.NET Core projects
The recommended way of creating new ASP.NET Core projects is via the installer:
Run the Xperience installer.
Select the Custom installation option and then the ASP.NET Core development model.
In the Installation type step, choose the New site option and enter a Name for your new site and project.
Configure the remaining options and finish the installation.
See Installing Xperience for a step-by-step guide.
After completing the installation, you have two separate web projects – a blank ASP.NET Core project suitable for the development of a new site, and an Xperience project that provides the content editing and administration interface. Both projects are connected to the same database and automatically configured to work together.
See next steps for a list of follow-up topics concerned with building Xperience applications.
If you already have an existing Xperience administration instance and do not wish to add new Core projects using the installer, you can also set up a new Core site manually. See Manually setting up ASP.NET Core projects.
Setting up local hosting for the Core application
You have two options when setting up a development hosting environment for the installed Core project:
- Host the Core application on the same domain under IIS together with the Xperience administration application (registered to IIS by the installation process).
- Host the Core application on a different domain.
Minimal APIs support
Xperience supports application hosting using the minimal APIs approach introduced in .NET 6. Hosting setup using this method is described on Hosting ASP.NET Core applications using minimal APIs.
Hosting on the same domain
In this case, you need to set up either in-process or out-of-process hosting under IIS. For a detailed configuration guide, see Host ASP.NET Core on Windows with IIS.
The main benefits of this approach are:
- no need to configure cookie SameSite.
- the site does not need to run under HTTPS (no need to generate a local SSL certificate).
Hosting on different domains
When hosting the Xperience administration and the Core live site project on different domains (e.g., when testing/debugging changes using IIS Express), you need to use HTTPS for both applications due to cookie SameSite requirements imposed by modern browsers. This involves performing the following:
- Set up hosting for the Core application. See Host and deploy ASP.NET Core.
- Generate and register development SSL certificates for your local servers.
- Configure Xperience to send cookies with the appropriate SameSite configuration.
This approach has the benefit of closely mimicking the final configuration of the production deployment.
Alternatively, you can use IKenticoServiceCollection.DisableVirtualContextSecurityForLocalhost from the Kentico.Web.Mvc namespace (present by default in the blank Core project created by the installation process). Call the method when adding application services in the ConfigureServices method in the application startup class.
The method ensures preview links work even without correctly set client-side cookies (due to missing SameSite prerequisites) by disabling the corresponding authentication checks. When using this configuration, you do not need to perform the aforementioned setup to get started developing locally.
Warning: Use DisableVirtualContextSecurityForLocalhost ONLY for local development. The method disables authentication checks for preview links, allowing anyone with valid preview URLs unrestricted access to the site.
public IWebHostEnvironment Environment { get; }
// Constructor for the application's startup class used to inject required dependencies
public Startup(IWebHostEnvironment environment)
{
Environment = environment;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var kenticoServiceCollection = services.AddKentico();
if (Environment.IsDevelopment())
{
kenticoServiceCollection.DisableVirtualContextSecurityForLocalhost();
}
...
}
Configuring application startup
The Xperience ASP.NET Core integration requires specific service and middleware components to function. You need to configure you application’s startup with the following requirements in mind.
Add the following services to the application’s container:
Xperience services – added via IServiceCollection.AddKentico.
The AddKentico call also adds a logging provider with the KenticoEventLog alias. The logging provider is built using conventional .NET Core logging API and by default logs all application errors to the Xperience event log. The logging severity and verbosity can be configured via application settings.
Support for controllers and views – added via IServiceCollection.AddControllersWithViews.
Authentication services – added via IServiceCollection.AddAuthentication.
And the project’s middleware pipeline needs to contain the following middleware:
- Static files (UseStaticFiles) – used by Xperience to serve files required by the page and form builder features, media library files, etc.
- Xperience middleware (UseKentico) – registers middleware and configuration required by the system. This call also adds the framework’s routing (UseRouting) and session (UseSession) middlewares.
- Cookie policy (UseCookiePolicy) – required due to the dual-application architecture of Xperience sites, for the system’s cookie support.
- Cross origin resource sharing (UseCors) – required due to Xperience’s dual-application architecture. You do not need to add the corresponding service classes (using IServiceCollection.AddCors) explicitly. These services are added as part of the IServiceCollection.AddKentico method.
- Authentication middleware (UseAuthentication) – required by certain system features, such as the page builder (when accessing the live site via the administration application).
The following code demonstrates required service registration and recommended middleware order. Ellipsis indicate breaks where other middleware may be inserted:
public void ConfigureServices(IServiceCollection services)
{
services.AddKentico();
services.AddControllersWithViews();
services.AddAuthentication();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseStaticFiles();
...
app.UseKentico();
...-
app.UseCookiePolicy();
...
app.UseCors();
...
app.UseAuthentication();
...
app.UseEndpoints(endpoints =>
{
// Adds system routes such as HTTP handlers and feature-specific routes.
endpoints.Kentico().MapRoutes();
...
});
}
The blank ASP.NET Core project created by the installation process comes with a startup class configured according to the specified requirements.
Configuring required middleware
The Xperience integration configures the required middleware using options from the application’s service container.
When adding custom middleware configuration for your project, do not configure middleware components directly within the corresponding UseMiddleware methods. If a configuration object is passed directly to middleware registration, the framework disregards all configuration stored in the service container. As Xperience relies on certain configuration options stored within the service container, overriding middleware configuration in this fashion will break Xperience functionality dependent on the corresponding middleware.
Instead, register custom middleware configuration directly within the application’s service container in ConfigureServices using IServiceCollection.ConfigureOptions methods. This way no configuration set by the Xperience integration gets overridden.
Options post-configuration
Xperience sets the following options during options post-configuration:
- SessionOptions.IdleTimeout to 20 minutes.
- SessionOptions.Cookie.IsEssential to true.
If you need to override these settings, call the PostConfigure method after IServiceCollection.AddKentico.
Setting up preview mode for pages
Preview mode in Xperience provides a way to view the latest version of pages before they are published (for example when using Workflows). The system supports preview mode by default, but you may need to set up and configure related functionality.
The configuration required to use preview mode differs based on your site’s routing mode:
- On sites using content tree-based routing, preview mode works automatically for all page types with the URL feature enabled.
- On sites running in the custom routing mode, you need to specify the URL pattern (in the Xperience administration) for your page types. The URL pattern is then used to create URLs to the content presented by the external application.
Preview URLs for pages are used in the following scenarios:
- When viewing pages in Preview mode in the Pages application.
- When editing pages via the page builder on the Page tab of the Pages application.
- When generating preview links for pages in Pages -> Properties -> URLs -> Preview URL. See: Sending links to unpublished pages
The preview URLs the system generates for pages consist of additional information, such as a hash for validating the URL.
Preview mode and cookie SameSite requirements
Preview mode is used by the Xperience administration to preview content from the live site application. The feature relies on certain cookies transmitted between the two applications to work correctly.
If your administration and live site applications are hosted on separate domains, you need to configure the system to send cookies with the appropriate SameSite mode when communicating under preview mode. See Configuring cookie SameSite mode.
Application configuration
This section covers miscellaneous configuration options you may wish to implement for your application.
Replacing the default service container
Xperience adds all of its services into the application’s IServiceCollection during the IServiceCollection.AddKentico() call in the ConfigureServices method. This approach is completely independent of the dependency injection provider used by the application. You can use any third-party service container that supports ASP.NET Core 3.1 or higher.
For example, to substitute the default Microsoft service container with Autofac:
Add the Autofac.Extensions.DependencyInjection NuGet package to your project.
In the CreateHostBuilder method call IHostBuilder.UseServiceProviderFactory(new AutofacServiceProviderFactory()).
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) // The UseServiceProviderFactory call attaches the // Autofac provider to the generic hosting mechanism. .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseStartup<Startup>(); });
(Optional) Add a ConfigureContainer(ContainerBuilder builder) method to your application’s startup class (Startup.cs by default). Within this method, you can add services using Autofac’s registration API. See the Autofac documentation for details.
The application now uses Autofac for dependency resolution.
Working with application settings
Xperience applications running on ASP.NET Core support the configuration provider approach for application settings. The system looks for application settings in the sources specified by the application’s IConfigurationBuilder .
Similar to any other .NET Core application, you can use the Microsoft.Extensions.Configuration.IConfiguration service to retrieve the values of individual keys. For example:
using Microsoft.Extensions.Configuration;
// Service instance provided by dependency injection
private readonly IConfiguration configuration;
// Retrieves the value of the 'CMSCIRepositoryPath' key
var path = configuration["CMSCIRepositoryPath"];
// Retrieves the value of the 'CMSConnectionString' key nested within the ConnectionStrings object
var connectionString = configuration["ConnectionStrings:CMSConnectionString"];
Application settings in .NET Core console applications
When calling Xperience API from console applications, the system is by default configured to look for application settings in a root-level app.config file. If you wish to store application settings in a different file or location, create a custom code-only module and substitute the default implementation with a custom IConfiguration provider during the module’s preinitilization. For example:
using Microsoft.Extensions.Configuration;
using CMS.Core;
...
protected override void OnPreInit()
{
// Registers a configuration provider configured to look
// for application settings in an 'appsettings.json' file.
// This overrides the default registration.
Service.Use<IConfiguration>(() => new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.Build());
}
Next steps
After you have a new project up and running, you can continue with building your website. Here are some topics to get you started:
Set up your ASP.NET Core site to provide a redirect that sends users to the administration interface of the connected Xperience instance upon accessing a predetermined URL (e.g., ~/admin). The redirect can provide a smoother experience for content editors and other staff working on the site by eliminating the need to manually switch between multiple domains. See Adding an administration redirect to ASP.NET Core sites for more information.