Search results

Create ASP.NET Web API Service

In this section, you will learn how to create a Web API Service for Report Designer using the new ASP.NET Empty Web Application template.

  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 the required .NET Framework in the drop-down.
  3. Select ASP.NET Web Application (.NET Framework), change the application name, and then click OK. Creating a new ASP.NET Web Application Project
  4. Then choose the empty application in template and click OK. Choosing a empty template in new Project

List of dependency libraries

The Web API service configuration requires reporting server-side assembly references.

  1. Right-click the project/solution in the Solution Explorer tab, and choose Manage NuGet Packages… Open nuget manager Alternatively, click Tools in menu, then select NuGet Package Manager | Manage NuGet Packages for Solution…

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

  2. Search for Syncfusion.Reporting.Web NuGet packages, and install them in your Web Forms application. Install reporting web package

  3. Syncfusion.Reporting.Web package will install the following required dependencies for Report Designer into your application. Click OK.

    Package Purpose
    Syncfusion.Reporting.Web Builds the server-side implementations.
  4. The above nuget package will automatically install below dependency packages.

    Packages Purpose
    Syncfusion.Pdf.AspNet Exports the report to a PDF.
    Syncfusion.DocIO.AspNet Exports the report to a Word.
    Syncfusion.XlsIO.AspNet Exports the report to an Excel.
    Syncfusion.Presentation.AspNet Exports the report to an PowerPoint.
  5. Install the Microsoft.AspNet.WebApi.Cors from Nuget to enable the Cross-Origin Resource Sharing (CORS) for Web API.

    Install-Package Microsoft.AspNet.WebApi.Cors

    This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. Browser security prevents Report Designer 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.

Add Routing Information

The following steps guide you to configure the routing to include an action name in the URI.

  1. Right-click the project in the solution explorer and select Add > New item.

  2. In the Add New Item window, select Global Application class and name it as Global.asax, and then click Add. Adding Global.asax file

  3. Open the code-behind file Global.asax.cs and add the following using statement.

        using System.Web.Http;
  4. Then add the the following code to the Application_Start method to register CORS.

        protected void Application_Start(object sender, EventArgs e)
        {
            System.Web.Http.GlobalConfiguration.Configuration.EnableCors();
        }

    For more information about CORS, see Configure CORS for WebAPI

  5. Add the following code to the Application_Start method to register the Routing configuration:

        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 });
        }

    For more information about routing tables, see Routing in ASP.NET Web API.

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 Web API Controller class and name it as ReportingAPIController, and then click Add. Adding a new controller to the project

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

Configure Web API

The IReportDesignerController interface contains the required actions and helper methods declaration to process the designer file and data actions. The ReportDesignerHelper and ReportHelper class contains methods that help to process Post or Get request from the control and return the response.

Methods Description
PostDesignerAction Action (HttpPost) method for posting the request for designer actions.
UploadReportAction Action (HttpPost) method for posted file actions.
UploadFile File upload method that is call while upload a file.
GetImage Action (HttpGet) method for getting resource for report images.
GetFilePath Get the path of specific file
GetFile Get the Specific file information
GetFiles Get the file list based on file type
PostReportAction Action (HttpPost) method for posting the request for report process.
GetResource Action (HttpGet) method for getting resource for report.
OnInitReportOptions Report initialization method that is triggered when the report begins to be processed.
OnReportLoaded Report loaded method that occurs when the report and sub report start loading.

ReportDesignerHelper

The class ReportDesignerHelper contains helper methods that help to process Post or Get request from the Report Designer control and returns the response to the Report Designer control. It has the following methods.

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

ReportHelper

The class ReportHelper contains helper methods that help process Post or Get request for report preview action and returns the response to the Report Designer. It has the following methods.

Methods Description
GetResource Returns the report resource for the requested key.
ProcessReport Processes the report request and returns the result.
  1. Open the ReportingAPIController and add the following using statement.

    using Syncfusion.Reporting.Web;
    using Syncfusion.Reporting.Web.ReportDesigner;
    using Syncfusion.Reporting.Web.ReportViewer;
  2. Next, add the [EnableCors] attribute to the ReportingAPIController class.

    [System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ReportingAPIController : ApiController
    {
    
    }
  3. Inherit the IReportDesignerController interface, and implement its methods (replace the following code in newly created Web API controller).

    [System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ReportingAPIController : ApiController, IReportDesignerController
    {
        public string GetFilePath(string fileName)
        {
            string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/");
            targetFolder += "Cache";
    
            if (!System.IO.Directory.Exists(targetFolder))
            {
                System.IO.Directory.CreateDirectory(targetFolder);
            }
    
            if (!System.IO.Directory.Exists(targetFolder + "\\" + ReportDesignerHelper.EJReportDesignerToken))
            {
                System.IO.Directory.CreateDirectory(targetFolder + "\\" + ReportDesignerHelper.EJReportDesignerToken);
            }
    
            var folderPath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Cache\\" + ReportDesignerHelper.EJReportDesignerToken + "\\";
            return folderPath + fileName;
        }
    
        [System.Web.Http.ActionName("GetImage")]
        [AcceptVerbs("GET")]
        public object GetImage(string key, string image)
        {
            return ReportDesignerHelper.GetImage(key, image, this);
        }
    
        public object PostDesignerAction(Dictionary<string, object> jsonResult)
        {
            return ReportDesignerHelper.ProcessDesigner(jsonResult, this, null);
        }
    
        public bool UploadFile(System.Web.HttpPostedFile httpPostedFile)
        {
            string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/");
            string fileName = !string.IsNullOrEmpty(ReportDesignerHelper.SaveFileName) ? ReportDesignerHelper.SaveFileName : System.IO.Path.GetFileName(httpPostedFile.FileName);
            targetFolder += "Cache";
    
            if (!System.IO.Directory.Exists(targetFolder))
            {
                System.IO.Directory.CreateDirectory(targetFolder);
            }
    
            if (!System.IO.Directory.Exists(targetFolder + "\\" + ReportDesignerHelper.EJReportDesignerToken))
            {
                System.IO.Directory.CreateDirectory(targetFolder + "\\" + ReportDesignerHelper.EJReportDesignerToken);
            }
    
            httpPostedFile.SaveAs(targetFolder + "\\" + ReportDesignerHelper.EJReportDesignerToken + "\\" + fileName);
            return true;
        }
    
        public void UploadReportAction()
        {
            ReportDesignerHelper.ProcessDesigner(null, this, System.Web.HttpContext.Current.Request.Files[0]);
        }
    
        [System.Web.Http.ActionName("GetResource")]
        [AcceptVerbs("GET")]
        public object GetResource(string key, string resourceType, bool isPrinting)
        {
            //Returns the report resource for the requested key.
            return ReportHelper.GetResource(key, resourceType, isPrinting);
        }
    
        public void OnInitReportOptions(ReportViewerOptions reportOption)
        {
            var resourcesPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Scripts");
    
            reportOption.ReportModel.ExportResources.Scripts = new List<string>
            {
                resourcesPath + @"\reports\common\ej.reporting.common.min.js",
                resourcesPath + @"\reports\common\ej.reporting.widgets.min.js",
                //Chart component script
                resourcesPath + @"\reports\data-visualization\ej.chart.min.js",
                //Gauge component scripts
                resourcesPath + @"\reports\data-visualization\ej.lineargauge.min.js",
                resourcesPath + @"\reports\data-visualization\ej.circulargauge.min.js",
                //Map component script
                resourcesPath + @"\reports\data-visualization\ej.map.min.js",
                //Report viewer Script
                resourcesPath + @"\reports\data-visualization\ej.chart.min.js",
                resourcesPath + @"\reports\ej.report-viewer.min.js"
            };
    
            reportOption.ReportModel.ExportResources.DependentScripts = new List<string>
            {
                resourcesPath + @"\jquery-1.7.1.min.js"
            };
        }
    
        public void OnReportLoaded(ReportViewerOptions reportOption)
        {
            //You can update report options here
        }
    
        public object PostReportAction(Dictionary<string, object> jsonResult)
        {
            return ReportHelper.ProcessReport(jsonResult, this as IReportController);
        }
    
        public FileModel GetFile(string filename, bool isOverride)
        {
            throw new NotImplementedException();
        }
    
        public List<FileModel> GetFiles(FileType fileType)
        {
            throw new NotImplementedException();
        }
    }
  4. Compile and run the Web API service application.