Report Controller

The ReportViewer uses Web API services to process the report file, process the request from control and return the processed data from control to client side.

IReportController

The interface IReportController has the declaration of action methods that is defined in WebApi Controller for processing the RDL/RDLC files and for processing request from ReportViewer control. The IReportController has the following action methods declaration.

Methods Description
GetResource Action (HttpGet) method for getting resource for report.
PostReportAction Action (HttpPost) method for posting the request for report process.
PostFormReportAction Action (HttpPost) method for posting the request for report exporting. It requires only in ASP.NET Core platform
OnInitReportOptions Report initialization method that is triggered when report begins to be processed.
OnReportLoaded Report loaded method that is triggered when report and sub report begin loading.

ReportHelper

The class ReportHelper contains helper methods that helps process Post/Get request from ReportViewer control and returns the response to ReportViewer control. The ReportHelper has the following methods.

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

Create a Web API Controller for .NET platform

Right-Click the Project, select Add and select Web API Controller Class file from the listed templates.

Getting-Started

Adding WebApi Controller

References

You should add the following assembly for the ReportViewer webAPI controller in .NET platform:

  • Syncfusion.Linq.Base
  • Syncfusion.Compression.Base
  • Syncfusion.EJ.ReportViewer
  • Syncfusion.Pdf.Base
  • Syncfusion.XlsIO.Base
  • Syncfusion.DocIO.Base
  • Syncfusion.Shared.Wpf
  • Syncfusion.Chart.Wpf
  • Syncfusion.Gauge.Wpf
  • Syncfusion.SfMaps.Wpf
  • Syncfusion.Licensing
  • Syncfusion.OfficeChart.Base
  • Syncfusion.Presentation.Base

NOTE

Refer the above assemblies from the installed location, C:\Program Files (x86)\Syncfusion\Essential Studio{platform}\16.4.0.42\Assemblies

Refer System.Web.Http, System. Web.Http.WebHost, System.Net.Http.WebRequest and System.Net.Http.Formatting assemblies from ASP.NET WebApi NuGet package.

Inherit IReportController

The ApiController inherits the IReportController and you can add the following code example to its methods definition in order to process the report file. The interface IReportController contains the required actions and helper methods declaration to process the report. The ReportHelper class contains helper methods that helps to process Post/Get request from control and return the response to control.

using Syncfusion.EJ.ReportViewer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ReportViewerDemo.Api 
{
    public class ReportApiController: ApiController,IReportController 
    {
        //Post action for processing the rdl/rdlc report 
        public object PostReportAction(Dictionary < string, object > jsonResult 
        {
            return ReportHelper.ProcessReport(jsonResult, this);
        }
        
        //Get action for getting resources from the report
        [System.Web.Http.ActionName("GetResource")]
        [AcceptVerbs("GET")]
        public object GetResource(string key, string resourceType, bool isPrint) 
        {
            return ReportHelper.GetResource(key, resourceType, isPrint);
        }
        
        //Method will be called when initialize the report options before start processing the report        
        public void OnInitReportOptions(ReportViewerOptions reportOption)
        {
            //You can update report options here
        }
        
        //Method will be called when reported is loaded
        public void OnReportLoaded(ReportViewerOptions reportOption) 
        {
            //You can update report options here
        }
    }
}

WebAPI Routing

  1. Right-Click the Project, select Add and select Global.asax file from the listed templates.

    Getting-Started

    Adding Global.asax

  2. You can route the WebAPI in Application_Start event into Global.asax file as follows.

       
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Security;
        using System.Web.SessionState;
        using System.Web.Http;
    	   
        namespace ReportViewerDemo 
        {
            public class Global: System.Web.HttpApplication 
            {
                protected void Application_Start(object sender, EventArgs e) 
                {
                    System.Web.Http.GlobalConfiguration.Configuration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional });
                }
            }
        }

Enable CORS

  1. Add the CORS NuGet package. In Visual Studio, goto the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
  • html
  • Install-Package Microsoft.AspNet.WebApi.Cors
    1. You can call enable cors method in Application_Start event into Global.asax file as follows.
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.Security;
        using System.Web.SessionState;
        using System.Web.Http;
    
        namespace ReportViewerDemo 
        {
            public class Global: System.Web.HttpApplication 
            {
                protected void Application_Start(object sender, EventArgs e) 
                {
                    System.Web.Http.GlobalConfiguration.Configuration.EnableCors();
                    System.Web.Http.GlobalConfiguration.Configuration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional });
                }
            }
        }
    1. Add the [EnableCors] attribute to the ApiController class as follows
        using Syncfusion.EJ.ReportViewer;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Net;
        using System.Net.Http;
        using System.Web.Http;
        using System.Web.Http.Cors;
        
        namespace ReportViewerDemo.Api 
        {
            [EnableCors(origins: "*", headers: "*", methods: "*")]
            public class ReportApiController: ApiController,IReportController 
            {
                //Post action for processing the rdl/rdlc report 
                public object PostReportAction(Dictionary < string, object > jsonResult 
                {
                    return ReportHelper.ProcessReport(jsonResult, this);
                }
                
                //Get action for getting resources from the report
                [System.Web.Http.ActionName("GetResource")]
                [AcceptVerbs("GET")]
                public object GetResource(string key, string resourceType, bool isPrint) 
                {
                    return ReportHelper.GetResource(key, resourceType, isPrint);
                }
                
                //Method will be called when initialize the report options before start processing the report        
                public void OnInitReportOptions(ReportViewerOptions reportOption)
                {
                    //You can update report options here
                }
                
                //Method will be called when reported is loaded
                public void OnReportLoaded(ReportViewerOptions reportOption) 
                {
                    //You can update report options here
                }
            }
        }

    Create a Web API Controller for .NET Core platform

    Right-Click the Project, select Add and select Web API Controller Class file from the listed templates.

    References

    You should add the following packages for the report viewer:

    Package Purpose
    Syncfusion.EJ.AspNet.Core Builds the report viewer controls with the tag helper.
    Syncfusion.EJ.ReportViewer.AspNet.Core Builds the server-side implementations.
    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 datasource. Also, the package version should be higher of 4.1.0 .

    If we install the above NuGet packages, it automatically add the below ReportViewer dependent NuGet file in your application,

    Package Purpose
    Syncfusion.EJ Builds the report viewer controls with the tag helper.
    Syncfusion.Report.Net.Core It is a base library for the Syncfusion.EJ.ReportViewer.AspNet.Corepackage.
    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.

    NOTE

    Please ensure all the above dependent packages are added properly after the NuGet package installation completed.

    Inherit IReportController

    The ApiController should inherit the IReportController interface to build the report viewer compatible Web API, and the ReportHelper should be used with IReportController interface implemented methods. The ReportHelper will perform the server-side related process and will return the required data for the report viewer to process the rendering. Here, the sample code is provided with an MVC application to build the Web API service along with the existing controller.

    Please add the following code example in controller page.

    using System.Collections.Generic;
    using Microsoft.AspNetCore.Mvc;
    
    namespace ReportViewerDemo.Controllers
    {
        public class HomeController : ApiController, Syncfusion.EJ.ReportViewer.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 HomeController(Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache, 
                Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
            {
                _cache = memoryCache;
                _hostingEnvironment = hostingEnvironment;
            }
    
            public IActionResult Index()
            {
                return View();
            }
    
            ...
            ...
            ...
    
            // Post action to process the report from server based json parameters and send the result back to the client.
            public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
            {
                return Syncfusion.EJ.ReportViewer.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(Syncfusion.EJ.ReportViewer.ReportViewerOptions reportOption)
            {
                string basePath = _hostingEnvironment.WebRootPath;
                // Here, we have loaded the sample report report from application the folder wwwroot. Sample.rdl should be there in wwwroot application folder.
                FileStream reportStream = new FileStream(basePath + @"\invoice.rdl", FileMode.Open, 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(Syncfusion.EJ.ReportViewer.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(Syncfusion.EJ.ReportViewer.ReportResource resource)
            {
                return Syncfusion.EJ.ReportViewer.ReportHelper.GetResource(resource, this, _cache);
            }
        }
    }

    WebAPI Routing

    You can route the WebAPI in configure method into Startup.cs file as follows.

     using Microsoft.AspNetCore.Builder;
     using Microsoft.AspNetCore.Hosting;
     using Microsoft.Extensions.Configuration;
     using Microsoft.Extensions.DependencyInjection;
     
     namespace ReportViewerDemo
     {
         public class Startup
         {
             public Startup(IConfiguration configuration)
             {
                 Configuration = configuration;
             }
     
             public IConfiguration Configuration { get; }
     
             // This method gets called by the runtime. Use this method to add services to the container.
             public void ConfigureServices(IServiceCollection services)
             {
                 services.AddMvc();
             }
     
             // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
             public void Configure(IApplicationBuilder app, IHostingEnvironment env)
             {
                 if (env.IsDevelopment())
                 {
                     app.UseDeveloperExceptionPage();
                 }
     
                 app.UseMvc();
     
                 app.UseMvc(routes =>
                 {
                     routes.MapRoute(
                         name: "default",
                         template: "api/{controller=ReportApi}/ {action=Index}/{id?}");
                 });
             }
         }
     }

    Enable CORS

    1. You can add cors in ConfigureServices method into Startup.cs file as follows.
        using Microsoft.AspNetCore.Builder;
        using Microsoft.AspNetCore.Hosting;
        using Microsoft.Extensions.Configuration;
        using Microsoft.Extensions.DependencyInjection;
    
        namespace ReportViewerDemo
        {
            public class Startup
            {
                public Startup(IConfiguration configuration)
                {
                    Configuration = configuration;
                }
    
                public IConfiguration Configuration { get; }
    
                // This method gets called by the runtime. Use this method to add services to the container.
                public void ConfigureServices(IServiceCollection services)
                {
                    services.AddMvc();
                    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                    {
                        builder.AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader();
                    }));
                }
    
                // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                {
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
    
                    app.UseMvc();
    
                    app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "default",
                            template: "api/{controller=ReportApi}/{action=Index}/{id?}");
                    });
                }
            }
        }
    1. Add the [EnableCors] attribute to the ApiController class as follows
        using System.Collections.Generic;
        using Microsoft.AspNetCore.Mvc;
        using Microsoft.AspNetCore.Cors;
    
        namespace ReportViewerDemo.Controllers
        {
            [EnableCors("MyPolicy")]
            public class HomeController : ApiController, Syncfusion.EJ.ReportViewer.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 HomeController(Microsoft.Extensions.Caching.Memory.IMemoryCache memoryCache, 
                    Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
                {
                    _cache = memoryCache;
                    _hostingEnvironment = hostingEnvironment;
                }
    
                public IActionResult Index()
                {
                    return View();
                }
    
                ...
                ...
                ...
    
                // Post action to process the report from server based json parameters and send the result back to the client.
                public object PostReportAction([FromBody] Dictionary<string, object> jsonArray)
                {
                    return Syncfusion.EJ.ReportViewer.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(Syncfusion.EJ.ReportViewer.ReportViewerOptions reportOption)
                {
                    string basePath = _hostingEnvironment.WebRootPath;
                    // Here, we have loaded the sample report report from application the folder wwwroot. Sample.rdl should be there in wwwroot application folder.
                    FileStream reportStream = new FileStream(basePath + @"\invoice.rdl", FileMode.Open, 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(Syncfusion.EJ.ReportViewer.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(Syncfusion.EJ.ReportViewer.ReportResource resource)
                {
                    return Syncfusion.EJ.ReportViewer.ReportHelper.GetResource(resource, this, _cache);
                }
            }
        }

    NOTE

    You cannot load the application report with path information in ASP.NET Core. So, you should load the report as Stream like an example provided above in OnInitReportOptions. If you need to get the invoice sample report then you can obtain it from the Syncfusion ASP.NET Core sample browser installed location (wwwroot\reports\invoice.rdl).