Chat Icon
Login-icon
Create an ASP.NET Core Web API Reporting Service in Bold Reports
Create an ASP.NET Core Web API Reporting Service in Bold Reports | ASP.NET Reporting Tools

Create an ASP.NET Core Web API Reporting Service in Bold Reports

This blog will walk you through how to create an ASP.NET Core Web API for the Report Viewer using the new ASP.NET Core web application template in Bold Reports. The Report Viewer comes with a wide range of report items to transform your business data into meaningful information so you can make bolder decisions.

The Report Viewer is a visualization control used to display SSRS RDL and RDLC reports within web applications. It allows you to view these reports with or without using SSRS.

Create a Web API project

  1. First, open Visual Studio 2019, click Create a new project and choose C# from the dropdown.
  2. Select ASP.NET Core Web Application (.NET Framework) and then click Next.

    Create a new project. | ASP.NET Core Reporting Tools
    Create a new project
  3. Change the application name to “ReportViewerCoreWebAPIand click Create.

    Configure a new project. | ASP.NET Core Reporting Tools
    Configure your new project

Note: The Bold Reports ASP.NET Core Report Viewer works in ASP.NET Core version 2.x and ASP.NET Core version 3.x.

  1. Choose ASP.NET Core 3.1, select the API application template, and click Create.

    Create a new ASP.NET Core web application. | ASP.NET Core Reporting Tools
    Create a new ASP.NET Core web application

Install the NuGet packages for ASP.NET Core Report

Let’s see how to install the NuGet packages.

  1. Right-click the project in the Solution Explorer tab and choose Manage NuGet Packages.

    Choose Manage NuGet Packages. | ASP.NET Core Reporting Tools
    Choose Manage NuGet Packages
  2. In the Browse tab, search for the BoldReports.Net.Core NuGet package and install it.

    : Install BoldReports.Net.Core NuGet package. | ASP.NET Core Reporting Tools
    Install BoldReports.Net.Core NuGet package

The BoldReports.Net.Core package is used to build the server-side implementations. The following table provides details about the dependency packages and their usage.

PackagePurpose
Syncfusion.Compression.Net.CoreUsed to export a report to PDF, Microsoft Word, and Microsoft Excel formats. It is a base library for the Syncfusion.Pdf.Net.Core, Syncfusion.DocIO.Net.Core, and Syncfusion.XlsIO.Net.Core packages.
Syncfusion.Pdf.Net.CoreUsed to export a report to a PDF.
Syncfusion.DocIO.Net.CoreUsed to export a report to Word.
Syncfusion.XlsIO.Net.CoreUsed to export a report to Excel.
Syncfusion.OfficeChart.Net.CoreA base library of the Syncfusion.XlsIO.Net.Core package.
Newtonsoft.JsonUsed to serialize and deserialize data for the Report Viewer. It is a mandatory package for Report Viewer. The package version should be higher than 10.0.1 for NET Core 2.0, and others should be higher than 9.0.1.

Add a Web API Controller in ASP.NET Core project

  1. Right-click the Controllers folder in your project and select Add > New Item from the context menu.

    Add a Web API controller. | ASP.NET Core Reporting Tools
    Add a Web API controller
  2. In the Add New Item dialog, select API Controller Class from the listed templates, name it ReportViewerController.cs, and then click Add.

    Select API Controller Class. | ASP.NET Core Reporting Tools
    Select API Controller Class
  3. Open the ReportViewerController and add the following using statement.
using BoldReports.Web.ReportViewer;
Add using statement. | ASP.NET Core Reporting Tools
Add using statement
  1. Inherit the IReportControllerinterface and then implement its methods using the next code snippet.
[Route("api/[controller]")]
public class ReportViewerController : Controller, IReportController
{
    // Report Viewer requires a memory cache to store the information of consecutive client requests and
    // have the rendered report viewer information in the server.
    private Microsoft.Extensions.Caching.Memory.IMemoryCache _cache;
    // IHostingEnvironment used with sample to get the application data from wwwroot.
    private Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;
    // Post action to process the report from server-based JSON parameters and send the result back to the client.
    public ReportViewerController(Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache,
        Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
    {
        _cache = memoryCache;
        _hostingEnvironment = hostingEnvironment;
    }
    // Post action to process the report from server based json parameters and send the result back to the client.
    [HttpPost]
    public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
    {
        return ReportHelper.ProcessReport(jsonArray, this, this._cache);
    }
    // Method will be called to initialize the report information to load the report with ReportHelper for processing.
    [NonAction]
    public void OnInitReportOptions(ReportViewerOptions reportOption)
    {
        string basePath = _hostingEnvironment.WebRootPath;
        // Here, we have loaded the sales-order-detail.rdl report from application the folder wwwroot\Resources. sales-order-detail.rdl should be there in wwwroot\Resources application folder.
        System.IO.FileStream reportStream = new System.IO.FileStream(basePath + @"\Resources\sales-order-detail.rdl", System.IO.FileMode.Open, System.IO.FileAccess.Read);
        reportOption.ReportModel.Stream = reportStream;
    }
    // Method will be called when reported is loaded with internally to start to layout process with ReportHelper.
    [NonAction]
    public void OnReportLoaded(ReportViewerOptions reportOption)
    {
    }
    //Get action for getting resources from the report.
    [ActionName("GetResource")]
    [AcceptVerbs("GET")]
    // Method will be called from Report Viewer client to get the image src for Image report item.
    public object GetResource(ReportResource resource)
    {
        return ReportHelper.GetResource(resource, this, _cache);
    }
    [HttpPost]
    public object PostFormReportAction()
    {
        return ReportHelper.ProcessReport(null, this, _cache);
    }
}

In the previous code, we loaded the sales-order-detail.rdl report from the Resources folder as basePath + @”\Resources\sales-order-detail.rdl.

IReportController interface

Declaration of action methods that are defined in the Web API Controller for processing:

  • RDL
  • RDLC
  • SSRS report
  • Handling resource requests from the Report Viewer control.

The IReportController has the following action methods declaration.

MethodsDescription
GetResourceUsed for getting resources for the report.
PostReportActionUsed for posting the request for the reporting process.
OnInitReportOptionsReport initialization method that is triggered when report begins to be processed.
OnReportLoadedReport loaded method that is triggered when report and subreport begin loading.

ReportHelper class

The ReportHelper class contains helper methods that help process POST or GET requests from the Report Viewer control and return the response to the Report Viewer control.

MethodsDescription
GetResourceReturns the report resource for the requested key.
ProcessReportProcesses the report request and returns the result.

Add Routing Information

Routing is the process of directing an HTTP request to a controller. The functionality of processing is implemented in System.Web.Routing.

Add the action parameter in the route template like in the following.

[Route("api/[controller]/[action]")]
public class ReportViewerController : Controller, IReportController
{
    // Report Viewer requires a memory cache to store the information of consecutive client requests and
    // have the rendered report viewer information in the server.
    private Microsoft.Extensions.Caching.Memory.IMemoryCache _cache;
    // IHostingEnvironment used with sample to get the application data from wwwroot.
    private Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;
    // Post action to process the report from server-based JSON parameters and send the result back to the client.
    public ReportViewerController(Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache,
        Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
    {
        _cache = memoryCache;
        _hostingEnvironment = hostingEnvironment;
    }
    // Post action to process the report from server based json parameters and send the result back to the client.
    [HttpPost]
    public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
    {
        return ReportHelper.ProcessReport(jsonArray, this, this._cache);
    }
    // Method will be called to initialize the report information to load the report with ReportHelper for processing.
    [NonAction]
    public void OnInitReportOptions(ReportViewerOptions reportOption)
    {
        string basePath = _hostingEnvironment.WebRootPath;
        // Here, we have loaded the sales-order-detail.rdl report from application the folder wwwroot\Resources. sales-order-detail.rdl should be there in wwwroot\Resources application folder.
        System.IO.FileStream reportStream = new System.IO.FileStream(basePath + @"\Resources\sales-order-detail.rdl", System.IO.FileMode.Open, System.IO.FileAccess.Read);
        reportOption.ReportModel.Stream = reportStream;
    }
    // Method will be called when reported is loaded with internally to start to layout process with ReportHelper.
    [NonAction]
    public void OnReportLoaded(ReportViewerOptions reportOption)
    {
    }
    //Get action for getting resources from the report
    [ActionName("GetResource")]
    [AcceptVerbs("GET")]
    // Method will be called from Report Viewer client to get the image src for Image report item.
    public object GetResource(ReportResource resource)
    {
        return ReportHelper.GetResource(resource, this, _cache);
    }
    [HttpPost]
    public object PostFormReportAction()
    {
        return ReportHelper.ProcessReport(null, this, _cache);
    }
}

Enable cross-origin requests

Browser security prevents Report Viewer from making requests to your Web API service when they run in different domains. To allow access to your Web API service from a different domain, you must enable cross-origin requests.

Open the Startup.cs file and call AddCors in Startup.ConfigureServices to add CORS services to the app’s service container. Add the following code to allow any origin requests.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
    {
        builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
    }));
}
Add CORS services to the app’s service container. | ASP.NET Core Reporting Tools
Add CORS services to the app’s service container

The Report Viewer uses MVC pattern controller actions for the report processing. To achieve this, call MVC and set EnableEndpointRouting to false.

services.AddMvc(m => m.EnableEndpointRouting=false);

Then, in the Configure method, add app.UseCors(); and app.UseMvc(); like in the following.

MVC pattern controller actions. | ASP.NET Core Reporting Tools
MVC pattern controller actions

Next, open the ReportViewerController.cs file, add the [EnableCors] attribute to the report viewer class and specify the policy name given in startup.configureservices.

Microsoft.AspNetCore.Cors.EnableCors(“AllowAllOrigins”)]
Specify the policy name. | ASP.NET Core Reporting Tools
Specify the policy name

Register a valid license token

Open the Startup.cs file and enter the code snippet to register the license token in the Application_Start method.

Bold.Licensing.BoldLicenseProvider.RegisterLicense("YOUR LICENSE TOKEN");

You can download license tokens from the Bold Reports site by referring to our documentation link.

Select Embedded Reporting > Generate License Token and copy the token.

In the Startup.cs file, register the license token. Then, compile and build the application.

You can host this service application on your machine. IIS, IIS Express, or Azure can be used for RDL report processing.

Everything required for report processing is ready.

Add the wwwroot folder to your application. Let’s create a simple JavaScript application to test the service action. You can refer to this blog to see how to create a simple JavaScript application.

Add created report

Create a Resources folder in the wwwroot folder in your application. This is where we will keep the RDL reports.

In this blog, the sales-order-detail.rdl file is added to the Resources folder. You can get the sales-order-detail.rdl file from this GitHub link.

Build and run the application, and you can see the weather forecast is launched by default.

Install Microsoft.AspNetCore.StaticFiles

Microsoft.AspNetCore.StaticFiles is a middleware package for serving:

  • Static files
  • Directory browsing
  • Default files

Now, stop debugging your application. Then, open Manage NuGet Packages. In the browse tab, search for Microsoft.AspNetCore.StaticFiles and install it.

In the Startup.cs file, add app.UseStaticFiles(); like in the following.

Add app.UseStaticFiles(). | ASP.NET Core Reporting Tools
Add app.UseStaticFiles()

Set the ReportPath and service URL

For testing purposes, set the following report service URL, which is relative to the index.html file.

reportServiceUrl: "./api/ReportViewer",
reportPath: "~/Resources/sales-order-detail.rdl"

To preview the report, compile and build the application. View the index.html file in the browser. You can see that the sales-order detail report is loaded in the Bold Report Viewer.

ASP.NET Core Web API for Report Viewer page. | ASP.NET Core Reporting Tools
ASP.NET Core Web API for Report Viewer page

Conclusion

In this blog, we learned how to create an ASP.NET Core Web API for the Report Viewer using the new ASP.NET Core Web Application template in Bold Reports. To explore further, go through our sample reports and Bold Reports documentation.

If you have any questions, please post them in the comments section. You can also contact us through our contact page, or if you already have an account, you can log in to submit your support question.

Bold Reports now comes with a 15-day free trial with no credit card information required. We welcome you to start a free trial and experience Bold Reports. Give it a try and let us know what you think!

Stay tuned to our official TwitterFacebookLinkedInPinterest, and Instagram pages for announcements about upcoming releases.

 

 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *