Building your first .NET Core app

Learn how to create your first website running on .NET Core MVC with Kentico Cloud.

New to Kentico Cloud?

If you're starting with Kentico Cloud, we suggest you begin with the Hello World tutorial, in which you'll learn the basics of creating content.

This tutorial will show you how to set up an ASP.NET Core MVC app from scratch and use it to display content from your Kentico Cloud project. If you're new to ASP.NET Core MVC, you might want to take the Getting started with ASP.NET Core MVC tutorial first.

You'll use the Kentico Cloud boilerplate (in other words, a template for new applications with a few basic features built on top of it) and customize it to suit your needs. The template includes features such as simple fixed-time caching, Delivery .NET SDK (for fetching content from your Kentico Cloud project), 404 error handling, logging, sitemap.xml generator, and more.

You will learn to:

  • Set up the app template
  • Connect your Kentico Cloud project
  • Add content type models
  • Render Rich text elements
  • Configure the app features

Requirements

Make sure you have the following installed:

Preparing the app template

Open a command line, register the ASP.NET Core MVC with Kentico Cloud custom template within your .NET Core templates by running the following command.

dotnet new --install "KenticoCloud.CloudBoilerplateNet::*"

Now you can initialize a new app based on that template.

dotnet new kentico-cloud-mvc --name "MyWebsite"

Your new web app is ready. Navigate to its folder and run it.

cd .\MyWebsite
dotnet run

Your app will start and be available at http://localhost:5000. Open the address in your browser to view it.

First run of the app

First run of the app

Connecting app to your project

Right now the app fetches content from the default Sample project and displays a preview of 3 articles.

To connect the app to your own project:

  1. In Kentico Cloud, choose Project settings from the app menu.
  2. Under Development, choose API keys.
  3. Copy the Project ID.
  4. In the app folder, open the appsettings.json file.
  5. Replace the value of the ProjectId key with the ID of your project.
  6. Save the changes.

When you now run the app again and open the http://localhost:5000 address in your browser, the app will work with data from the specified project.

Adding content type models

To make further app development easier, we recommend using the Kentico Cloud model generator for .NET to create strongly-typed models representing your content types. To learn more about this approach generally, see Using strongly typed models.

Sample models

By default, the app template comes with a single model describing the structure of an Article content type – you can find the model in the \Models\ContentTypes\ folder.

The Article model is referenced as an example in multiple locations across the template:

  • \Controllers\HomeController.cs.
  • \Controllers\SiteMapController.cs
  • \Views\Home\Index.cshtml
  • \Views\Shared\DisplayTemplates\Article.cshtml

You can adjust these references later when you customize the app.

Your project will likely have other content types with different structure than the included sample models. This means you can safely overwrite the contents of the \Models\ContentTypes\ folder with your own models.

1. Generating models

First, clone the GitHub repository with the model generator to your drive.

git clone https://github.com/Kentico/cloud-generators-net.git

Next, in your command line, navigate to .\cloud-generators-net\src\CloudModelGenerator\ and use the dotnet run command with the following parameters:

  • --projectid – specifies the ID of your Kentico Cloud project.
  • --withtypeprovider – tells the generator to create the CustomTypeProvider class to support runtime type resolution.
  • --structuredmodel – tells the generator to type Rich text elements as IRichTextContent objects instead of strings.
  • --outputdir – specifies where to store the generated models.
  • --namespace – specifies the namespace of the generated models.
# Sets the working directory
cd .\cloud-generators-net\src\CloudModelGenerator\

# Note: This overwrites existing files in the Models\ContentTypes folder
dotnet run --projectid "<YOUR_PROJECT_ID>" --withtypeprovider --structuredmodel --outputdir "<PATH_TO_YOUR_APP>\Models\ContentTypes" --namespace "MyWebsite.Models"

The models are generated as partial classes. This means you can extend them in separate files and re-generate the models in the future without losing your custom code. If you'd like to learn more about the data types used for individual content elements, see Working with strongly typed models.

2. Mapping retrieved content to models

Now, when you fetch content items from your project, you can map the returned data to a specific model.

// Retrieves a list of Article content items
DeliveryItemListingResponse<Article> response = await DeliveryClient.GetItemsAsync<Article>(
    new EqualsFilter("system.type", "article"),
    new LimitParameter(3),
    new DepthParameter(0),
    new OrderParameter("elements.post_date")
);

// Sends the strongly-typed content items to a View
return View(response.Items)

You can find the code in the HomeController controller.

Mapping to your models

Use the same approach to map your content to the models of your content types. Make sure you adjust the following when retrieving content:

  • Replace instances of Article with the name of the class representing your content type.
  • Replace article in the EqualsFilter parameter with the codename of your content type.
  • Replace the value of the OrderParameter so that the API orders the results by values in existing elements or system attributes. For more details, see Ordering.

If you want to learn more about content filtering in .NET, check out Getting to Know the Kentico Cloud .NET SDK Delivery API Filters.

3. Displaying content

After that, you can access any of the content type's elements (as model properties) in the app's Views.

@model Article

<div class="body">
  <h2>@Model.Title</h2>

  <img src="@Model.TeaserImage.First().Url" class="img-responsive" alt="@Model.TeaserImage.First().Name"/>

  @Model.Summary
</div>

If you're using a different model, be sure to change the model declaration and individual properties.

Rendering Rich text elements

To render Rich text elements, use the Html.DisplayFor helper method in your Views.

@* Renders content of a Rich text element (BodyCopy in an article) *@
@Html.DisplayFor(model => model.BodyCopy)

Right now, individual blocks of content in Rich text elements will be rendered using their default HTML representation, matching the content returned by the Delivery API. But you can also write your own representations of rich content.

Rendering rich content

To customize the way your app renders components, content items and inline images, you need to provide display templates for them:

  • Components and content items – display template named <ModelName>.cshtml where the ModelName refers to the content type of the content item or component, for example, Tweet.cshtml.
  • (Optional) Inline images – display template named InlineImage.cshtml.

For a more in-depth example, see Structured Rich text rendering.

Resolving URLs

If your Rich text elements contain links to other content items, you need to tell your app how to form correct URLs.

To do this, open the Resolvers\CustomContentLinkUrlResolver.cs file in your app and add implementation to the following methods:

  • ResolveLinkUrl – used when the linked content item is available.
  • ResolveBrokenLinkUrl – used when the linked content item is not available.

Note that both methods must return strings.

See the example below and add more logic based on your content types.

public string ResolveLinkUrl(ContentLink link)
{
    // Resolves links pointing to Article content items
    if (link.ContentTypeCodename.Equals(Article.Codename))
    {
        return $"/articles/{link.UrlSlug}";
    }

    // Add the rest of the resolver logic
}

public string ResolveBrokenLinkUrl()
{
    // Resolves URLs to unavailable content items
    return "/Error/404";
}

If you want to learn more about the way these resolvers work, see Resolving links to content items.

Configuring the app

The app template also includes a set of pre-configured features such as error handling, fixed-time caching, sitemap.xml generator, and others. You can configure most of these features in the Startup.cs file.

Error handling

When you run the app locally on your machine without specifying any environment-specific launch profile, the app will use a development profile. This means that if your app encounters an exception, it will be logged to the console and displayed directly in your browser.

In a production environment (that is when the app is run with a production profile), all errors are still logged, but a custom error page is displayed instead of the stack trace.

If you'd like to tweak the error handling and relevant error pages, see the following:

  • The Configure method in the Startup class – specifies app behavior in different environments.
  • The ErrorController controller – specifies what pages to display for specific HTTP status codes such as 404 Not Found.
  • The views in the Views\Error folder – contain pages that are displayed when an error occurs in a production environment.

Caching

To use fewer Content API calls, the app employs a fixed-time caching mechanism and stores the retrieved content in its memory for 5 minutes. Without any caching, you would be making requests to the Delivery API with each page load. You can set a different time by changing the CacheTimeoutSeconds key in the appsettings.json file.

What's next?

The basic skeleton of your new app is now ready. We recommend you use it as a starting point and add more functionality where needed.

For example, you might find inspiration in the following:

  • Sample .NET MVC application – includes examples of View Models and Display Templates.
  • Using MVC - Display Templates Basics – this multi-part tutorial will help you get started building the face of your app with display templates. Use them for specifying the look of components, content items and images in Rich text elements, and other parts of your app.
  • Learn about the ways to filter and sort the content you retrieve from your project in Getting content.