The following article is applicable to Telerik Reporting versions R2 2019 and above. It elaborates on how to host Telerik Reporting REST Service and add HTML5 Report Viewer in an ASP.NET Core 3+ web application.

Designing the Reports

For design-time support, it is recommended to use the Standalone Report Designer for creating reports or migrate the existing ones to TRDP/TRDX report definitions. The other available approach is designing reports in a separate Telerik Report Library created against .NET Framework 4.0+ which later must be migrated to a .NET Standard or .NET Core library. For more information, please refer to Guidance for using reports from an existing .NET Framework 4+ report library in a .NET Core application knowledge based article. Design-time support is not yet provided for .Net Core Telerik Report Library (Class Library) projects storing the report definitions.

Supported Environment

The recommended way to reference the Telerik Reporting assemblies into Core projects is to install their NuGet packages. The assemblies are available in the \Bin\netcoreapp3.0\ folder of Telerik Reporting installation directory as well. The external dependencies are resolved through NuGet package dependencies in order to provide better dependency management and code portability. The Reporting engine relies on the GDI+ API which is available on the Windows OS. On Linux and macOS we use library called libgdiplus instead. The GDI+ API is required for measuring, laying out, rendering the text glyphs and images.

Connection Strings and Engine Configuration

.NET Core applications provide new way of storing the configuration - a key-value JSON-based file named appSettings.json. To activate JSON file configuration, call the AddJsonFile extension method on an instance of ConfigurationBuilder. Add a new class, for example named ConfigurationService to your application assets as shown below:

C#
public class ConfigurationService
{
    public IConfiguration Configuration { get; private set; }

    public IWebHostEnvironment Environment { get; private set; }
    public ConfigurationService(IWebHostEnvironment environment)
    {
        this.Environment = environment;

        var configFileName = System.IO.Path.Combine(environment.ContentRootPath, "appsettings.json");
        var config = new ConfigurationBuilder()
                        .AddJsonFile(configFileName, true)
                        .Build();

        this.Configuration = config;
    }
}

Add a singleton service of type ConfigureService to the container services (ConfigureServices method).

C#
this.services.AddSingleton<ConfigurationService>();

In .NET Core 3 by default Synchronous operations are disallowed. Synchronous operations are necessary to download resources such as images used in the reports. They need to be manually allowed, for example by setting the AllowSynchronousIO to True in the container services.

C#
this.services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

Finally, all configurations should be placed in appsettings.json. For example ConnectionStrings setting should be configured in JSON-based format like this:

JSON
{
  ...
  "ConnectionStrings": {
    "Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString": "Data Source=.\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=true"
  }
}

The above type of connection string lacks information about the data provider and will use System.Data.SqlClient as provider invariant name. When it's necessary to specify a different data provider, the following notation is also supported:

JSON
{
  ...
  "ConnectionStrings": {
    "Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString": {
      "connectionString": "Data Source=.\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=true",
      "providerName": "System.Data.SqlClient"
    }
  }
}

The two types of connection string notations specified above can coexist in a single ConnectionStrings section.

The last supported type of ConnectionStrings configuration uses an array to provide information about each connection string:

JSON
{
  ...
  "ConnectionStrings": [
    {
      "name": "Telerik.Reporting.Examples.CSharp.Properties.Settings.TelerikConnectionString",
      "connectionString": "Data Source=.\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=true",
      "providerName": "System.Data.SqlClient"
    }
  ]
}

Prerequisites

Creating a Sample ASP.NET Core 3 Project

  1. Open Visual Studio 2019.

  2. From the File menu, select New > Project.

  3. In the Add a new Project dialog select ASP.NET Core Web Application project template. Choose a name and location for the project and click Create.

  4. In the Create a new ASP.NET Core web application dialog select from the drop downs .NET Core and ASP.NET Core 3.0. Next from the list of templates select Empty project template and click Create.

Adding the required NuGet Packages

In the Requirements section, there are listed the NuGet packages that need to be included to a .NET Core application that uses Telerik Reporting. These dependencies are automatically resolved when using the Telerik.Reporting.Services.AspNetCore package. Otherwise they need to be manually added to the project.

To setup the Reporting REST service reference Telerik.Reporting.Services.AspNetCore NuGet package from the private Telerik NuGet feed at https://nuget.telerik.com/nuget. How to add a NuGet feed is explained in https://www.visualstudio.com/en-us/docs/package/nuget/consume. Telerik account is required to access the private repository. The Telerik.Reporting package will be added automatically as Telerik.Reporting.Services.AspNetCore dependends on it.

The Reporting tool uses Newtonsoft.Json and you need to add Microsoft.AspNetCore.Mvc.NewtonsoftJson (3.0.0)+ NuGet package.

For Office OpenXML document formats (XLSX, DOCX and PPTX) install the DocumentFormat.OpenXML and Telerik.Reporting.OpenXmlRendering NuGet packages. The DocumentFormat.OpenXML package support out of the box version 2.7.2.0 and above.

Setting up the ConfigurationService in the Startup.cs file

  1. Add the ConfigurationService class as a separate file or in the Startup.cs file

  2. Add the required services in the Configure method

    C#
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        this.services.AddTransient(ctx => new Controllers.ReportsController(new ConfigurationService(env)));
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseStaticFiles();
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

Finally, the Startup.cs file should look like :

C#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Html5Viewer
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        private IServiceCollection services;

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            this.services = services;

            this.services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            this.services.AddSingleton<ConfigurationService>();

            services.AddRazorPages()
                .AddNewtonsoftJson();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            this.services.AddTransient(ctx => new Controllers.ReportsController(new ConfigurationService(env)));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();// must
            app.UseRouting();// must

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();// must
            });
        }
    }

    public class ConfigurationService
    {
        public IConfiguration Configuration { get; private set; }

        public IWebHostEnvironment Environment { get; private set; }
        public ConfigurationService(IWebHostEnvironment environment)
        {
            this.Environment = environment;

            var configFileName = System.IO.Path.Combine(environment.ContentRootPath, "appsettings.json");
            var config = new ConfigurationBuilder()
                            .AddJsonFile(configFileName, true)
                            .Build();

            this.Configuration = config;
        }
    }
}

Setting up the REST service

  1. Create folder Controllers. Right-click on the project name and select Add > New folder. Name it Controllers.

  2. Implement a Reports controller. Right-click on the Controllers folder and add a new item: Add > New item > Web API Controller Class item. Name it ReportsController. This will be our Telerik Reporting REST service in the project.

  3. Inherit the ReportsControllerBase type and provide proper settings for ReportResolver and Storage. This is how a basic implementation of the controller should look like:

    C#
    using Microsoft.AspNetCore.Mvc;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Mail;
    using Telerik.Reporting.Cache.File;
    using Telerik.Reporting.Services;
    using Telerik.Reporting.Services.AspNetCore;
    
    namespace CSharp.AspNetCoreDemo.Controllers
    {
        [Route("api/reports")]
        public class ReportsController : ReportsControllerBase
        {
            readonly string reportsPath = string.Empty;
    
            public ReportsController(ConfigurationService configSvc)
            {
                this.reportsPath = Path.Combine(configSvc.Environment.WebRootPath, "Reports");
    
                this.ReportServiceConfiguration = new ReportServiceConfiguration
                {
                    ReportingEngineConfiguration = configSvc.Configuration,
                    HostAppId = "Html5DemoAppCore",
                    Storage = new FileStorage(),
                    ReportResolver = new ReportTypeResolver()
                                        .AddFallbackResolver(new ReportFileResolver(this.reportsPath)),
                };
            }
    
            [HttpGet("reportlist")]
            public IEnumerable<string> GetReports()
            {
                return Directory
                    .GetFiles(this.reportsPath)
                    .Select(path =>
                        Path.GetFileName(path));
            }
            protected override HttpStatusCode SendMailMessage(MailMessage mailMessage)
            {
                throw new System.NotImplementedException("This method should be implemented in order to send mail messages");
                //using (var smtpClient = new SmtpClient("smtp01.mycompany.com", 25))
                //{
                //    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                //    smtpClient.EnableSsl = false;
    
                //    smtpClient.Send(mailMessage);
                //}
                //return HttpStatusCode.OK;
            }
    
        }
    }

Adding the HTML5 Report Viewer

  1. To set up a folder for the reports, right-click on wwwroot and select Add > New Folder. Name the folder Reports and add sample reports in TRDP format. Find the sample reports in {Telerik Reporting installation path}\Report Designer\Examples Note that the name of the folder is considered with the folder path used by the ReportFileResolver in the ReportsController.

    This tutorial will use Barcodes Report.trdp in the examples folder.

  2. Add a HTML Page for the HTML5 Report Viewer by right-clicking on wwwroot and Add > New Item... > HTML Page. Name the file index.html and add the HTML5 Report Viewer's initialization. For a detailed explanation, check the HTML5 Report Viewer Manual Setup help article. The required references to jQuery and Telerik Kendo UI CSS and JS files are listed in the example below. By default the necessary Report Viewer scripts and styles are served by the REST Service.

    The complete report viewer page should look like this:

    HTML
    <!DOCTYPE html> 
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head> 
      <title>Telerik HTML5 Report Viewer Demo in ASP.NET Core</title>
    
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
    
      <link href="http://kendo.cdn.telerik.com/2019.1.115/styles/kendo.common.min.css" rel="stylesheet" /> 
      <link href="http://kendo.cdn.telerik.com/2019.1.115/styles/kendo.blueopal.min.css" rel="stylesheet" /> 
    
      <script src="/api/reports/resources/js/telerikReportViewer"></script>
    
      <style> 
          #reportViewer1 { 
              position: absolute; 
              left: 5px; 
              right: 5px; 
              top: 50px; 
              bottom: 5px; 
              overflow: hidden; 
              font-family: Verdana, Arial; 
          } 
      </style> 
    
    </head> 
    <body> 
      <div id="reportViewer1"> 
          loading... 
      </div> 
    
      <script> 
          $(document).ready(function () { 
              $("#reportViewer1") 
                  .telerik_ReportViewer({ 
                      serviceUrl: "api/reports/", 
                      reportSource: { 
                          report: "Barcodes Report.trdp", 
                          parameters: {} 
                      }, 
                      viewMode: telerikReportViewer.ViewModes.INTERACTIVE, 
                      scaleMode: telerikReportViewer.ScaleModes.SPECIFIC, 
                      scale: 1.0,
                      enableAccessibility: false,
                      sendEmail: { enabled: true }
                  }); 
          }); 
      </script> 
    </body> 
    </html>
  3. Set the launchSettings.json launchUrl to the new HTML page.

  4. Finally, run the project to see the report.

See Also

Other Resources

In this article
Not finding the help you need?