Search results

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:

  1. Open Visual Studio 2017, click the File menu, go to New, and then select Project.
  2. Go to Installed > Visual C# > Web, and then select ASP.NET Core Web Application, change the application name, and then click OK.
  3. Choose the ASP.NET Core version and select the API application template and click OK. Do not select Enable Docker Support. Creating a new ASP.NET Core Application Project

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 Syncfusion.Reporting.Net.Core package, and install to the application. The following provides detail of the packages and its usage.

Package Purpose
Syncfusion.Reporting.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 Syncfusion.Reporting.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.
    IHostingEnvironment IHostingEnvironment used to get the report stream from application wwwroot\Resources folder.
  7. You cannot load the application report with path information in ASP.NET Core service. So, you should load the report as stream in OnInitReportOptions.

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

    [Route("api/[controller]/[action]")]
    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;
    
        // 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.
        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.
        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 Syncfusion installation location. For more information on installed sample location, see Samples and demos.

  9. 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 Startup.ConfigureServices to add the CORS services to the app’s service container. Replace the following code to allow any origin requests.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
    {
        builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
    }));
}

To specify the CORS policy for the controller, add the [EnableCors] attribute to the controller class. Specify the policy name.

[Microsoft.AspNetCore.Cors.EnableCors("AllowAllOrigins")]
public class ReportViewerController : Controller, IReportController
{
    public IActionResult Index()
    {
        return View();
    }
    ....
}