Search results
Suggest a FeaturePDF

Create ASP.NET Core Web API Service

To create an ASP.NET Core Web API for Report Viewer using a new ASP.NET Core Web Application template, follow these steps:

Bold Reports ASP.NET Core supports from .NET Core 2.1 only. So, choose the .NET Core version ASP.NET Core 2.1 or higher versions for Viewer API creation.

To get start quickly with ASP.NET Core Web API for Report Viewer, you can check on this video:

  1. Start Visual Studio 2022 and click Create new project.
  2. Choose ASP.NET Core Web API, and then click Next.

Creating a new ASP.NET Core Application Project 3. Change the project name, and then click Next. 4. In the dropdown for the ASP.NET Core version, choose ASP.NET Core 6.0, then click Create. Creating a new ASP.NET Core Application Framework

If you need to use Bold Reports with ASP.NET Core on Linux or macOS, then refer to this Can Bold Reports be used with ASP.NET Core on Linux and macOS section.

List of dependency Libraries

The Web API service configuration requires the following reporting server-side packages. Right-click the project or solution in the Solution Explorer tab, and choose Manage NuGet Packages and then search for BoldReports.Net.Core package, and install to the application. The following provides detail of the packages and its usage.

Package Purpose
BoldReports.Net.Core Builds the server-side implementations.

Refer to the NuGet Packages section to learn more details about installing and configuring Report Viewer NuGet packages.

The following table provides details about the dependency packages and its usage.

Package Purpose
Syncfusion.Compression.Net.Core Supports for exporting the report to PDF, Microsoft Word, and Microsoft Excel format. It is a base library for the packages Syncfusion.Pdf.Net.Core , Syncfusion.DocIO.Net.Core and Syncfusion.XlsIO.Net.Core.
Syncfusion.Pdf.Net.Core Supports for exporting the report to a PDF.
Syncfusion.DocIO.Net.Core Supports for exporting the report to a Word.
Syncfusion.XlsIO.Net.Core Supports for exporting the report to an Excel.
Syncfusion.OfficeChart.Net.Core It is a base library of the Syncfusion.XlsIO.Net.Core package.
Newtonsoft.Json Serialize and deserialize the data for report viewer. It is a mandatory package for the report viewer, and the package version should be higher of 10.0.1 for NET Core 2.0 and others should be higher of 9.0.1.
System.Data.SqlClient This is an optional package for the report viewer. It should be referred in project when renders the RDL report and which contains the SQL Server and SQL Azure data source. Also, the package version should be higher of 4.1.0.

Configure Web API

The interface IReportController has declaration of action methods that are defined in the Web API Controller for processing the RDL, RDLC, and SSRS reports and for handling request from the Report Viewer control. The IReportController has the following action methods declaration:

Methods Description
PostReportAction Action (HttpPost) method for posting the request in report process.
OnInitReportOptions Report initialization method that occurs when the report is about to be processed.
OnReportLoaded Report loaded method that occurs when the report and sub report start loading.
GetResource Action (HttpGet) method to get resource for the report.

ReportHelper

The class ReportHelper contains helper methods that help to process a Post or Get request from the Report Viewer control and return the response to the Report Viewer control. It has the following methods:

Methods Description
GetResource Returns the report resource to the requested key.
ProcessReport Processes the report request and returns the result.

Add Web API Controller

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

  2. In the Add New Item dialog, select API Controller class and name it as ReportViewerController.cs Adding a new controller to the project

  3. Click Add.

    While adding API Controller class, name it with the suffix Controller that is mandatory.

  4. Open the ReportViewerController and add the following using statement.

    using BoldReports.Web.ReportViewer;
  5. Inherit the IReportController interface, and then implement its methods.

  6. Create local references for the interfaces given in following table.

    Interface Purpose
    IMemoryCache Report Viewer requires a memory cache to store the information of consecutive client request and have the rendered report viewer information in server.
    IWebHostEnvironment IWebHostEnvironment used to get the report stream from application wwwroot\Resources folder.
  7. Next, add the [EnableCors] attribute to the ReportViewerController class and specify the policy name which given in Program.cs.

    [Route("api/[controller]/[action]")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAllOrigins")]
    public class ReportViewerController : Controller, IReportController
    {
    }
  8. You cannot load the application report with path information in ASP.NET Core service. So, you should load the report as stream in OnInitReportOptions.

            [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;
            }
  9. You can replace the template code with the following code.

    [Route("api/[controller]/[action]")]
    [Microsoft.AspNetCore.Cors.EnableCors("AllowAllOrigins")]
    public class ReportViewerController : Controller, IReportController
    {
        // Report viewer requires a memory cache to store the information of consecutive client request and
        // have the rendered report viewer information in server.
        private Microsoft.Extensions.Caching.Memory.IMemoryCache _cache;
    
        // IWebHostEnvironment used with sample to get the application data from wwwroot.
        private Microsoft.AspNetCore.Hosting.IWebHostEnvironment _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.IWebHostEnvironment 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);
        }
    }

    The sales-order-detail.rdl report can be downloaded from here. Also, you can add the report from Bold Reports installation location. For more information on installed sample location, see Samples and demos.

  10. Run the application and use the API URL http://localhost:port_number/Home in the Report Viewer reportServiceUrl property.

Enable Cross-Origin requests

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

Call AddCors in Program.cs to add the CORS services to the app’s service container. Replace the following code to allow any origin requests.

    builder.Services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
    {
    builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
    }));

    .......
    .......

    app.UseHttpsRedirection();
    app.UseCors();
    app.UseAuthorization();

For more information about CORS, see Configure CORS for API