如何在Web API应用程序中使用FastReport

下载FastReport.Net最新版本

在本文中,我们将创建一个用于从服务器接收FastReport报表的API。首先,让我们定义API是什么。从字面上看,这个缩写代表了应用程序的软件界面。这意味着应用程序具有提供对其功能的访问的接口。在Web应用程序的上下文中,API是一种Web服务,具有一组与后端(应用程序或数据库)交互的方法。换句话说,系统对我们来说是一个黑盒子,只有Web方法允许我们使用它。

因此,我们确定Web Api是一个带有一组Web方法的Web服务。这些可以是HTTP协议支持的四种基本CRUD功能。它们由请求实现:GET - 读取,POST - 创建,PUT - 更改,DELETE - 删除。

我们将在本文中创建此Web应用程序。而专为.Net Core框架设计的FastReport.Core将为我们生成报表。 创建一个ASP .Net Core Web应用程序。在向导的第二步中创建一个新项目,您可以选择Web应用程序的类型 - Web API:

首先,我们需要使用Nuget包管理器连接库。

要安装FastReport.Core和FastReport.Web包,您需要选择本地存储库。但是,它必须配置。在存储选择下拉列表旁边有一个齿轮图标。单击它并查看设置窗口:

选择“Local package source”并更改源的路径。然后,单击“Update”按钮。现在,在包管理器中,我们可以安装FastReport.Core和FastReport.Web。 在我们的演示中,我们将了解如何从服务器下载报表,如何在浏览器中查看报表以及如何将参数传递给报表。因此,我们将使用的主要实体是报表。让我们将Reports类添加到数据模型中,该模型将包含两个字段:Id - 报表标识符,ReportName - 报表名称。

模型Reports.cs

 public class Reports
 {
 // Report ID
 public int Id { get; set; }
 // Report File Name
 public string ReportName { get; set; }
 }

在Controllers包中,默认情况下有一个ValuesController.cs类。我们用它。 在使用部分,我们需要库:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using WebApiCore.Models;
using System.IO;
using System.Data;
using FastReport.Utils;
using FastReport;
using FastReport.Export.Html;
using FastReport.Export.Pdf;

用于接收报表的URL可能包含其他参数:报表文件的格式,内联显示的符号,传递给报表的参数。将包含必填字段的类添加到控制器:

public class ReportQuery
 {
 // Format of resulting report: png, pdf, html
 public string Format { get; set; }
 // Enable Inline preview in browser (generates "inline" or "attachment")
 public bool Inline { get; set; }
 // Value of "Parameter" variable in report
 public string Parameter { get; set; }
 }

我们需要两个我们将演示的报表模板和一个数据库。我们使用交付的报表:Master-Detail.frx和Barcodes.frx。第一个报表的nwind.xml数据库也来自FR的交付。我们将这三个文件放在App_Data文件夹中,该文件夹将在wwwroot目录中创建。

控制器类可以具有执行路由角色的Route属性。这意味着此类仅接受来自指定路径的请求。我将使用注释来解释代码,以及方法之间的文本插入。

[Route("api/[controller]")]
 public class ValuesController : Controller
 {
 private readonly IHostingEnvironment _hostingEnvironment; // Use the web hosting environment interface to get the root path
 public ValuesController(IHostingEnvironment hostingEnvironment)
 {
 _hostingEnvironment = hostingEnvironment;
 }
// Create a collection of data of type Reports. Add two reports.
 Reports[] reportItems = new Reports[]
 {
 new Reports { Id = 1, ReportName = "Master-Detail.frx" },
 new Reports { Id = 2, ReportName = "Barcode.frx" }
 };

在控制器中获取数据的默认方法是Get。通常它有一个重载版本,就像我们的情况一样。动作方法通常具有关联属性。该属性可以具有参数。

[HttpGet]
 public IEnumerable<Reports> Get()
 {
 return reportItems; // Returns a list of reports.
 }

// Attribute has required id parameter
 [HttpGet("{id}")]
 public IActionResult Get(int id, [FromQuery] ReportQuery query)
 {
 string mime = "application/" + query.Format; // MIME header with default value
 // Find report
 Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); // we get the value of the collection by id
 if (reportItem != null)
 {
 string webRootPath = _hostingEnvironment.WebRootPath; // determine the path to the wwwroot folder
 string reportPath = (webRootPath + "/App_Data/" + reportItem.ReportName); // determine the path to the report
 string dataPath = (webRootPath + "/App_Data/nwind.xml");// determine the path to the database
 using (MemoryStream stream = new MemoryStream()) // Create a stream for the report
 {
 try
 {
 using (DataSet dataSet = new DataSet())
 {
 // Fill the source by data
 dataSet.ReadXml(dataPath);
 // Turn on web mode FastReport
 Config.WebMode = true;
 using (Report report = new Report())
 {
 report.Load(reportPath); // Download the report
 report.RegisterData(dataSet, "NorthWind"); // Register data in the report
 if (query.Parameter != null)
 {
 report.SetParameterValue("Parameter", query.Parameter); // Set the value of the report parameter if the parameter value is passed to the URL
 }
 report.Prepare();//Prepare the report
 // If pdf format is selected
 if (query.Format == "pdf")
 {
 // Export report to PDF
 PDFExport pdf = new PDFExport();
 // Use the stream to store the report, so as not to create unnecessary files
 report.Export(pdf, stream);
 }
 // If html report format is selected
 else if (query.Format == "html")
 {
 // Export Report to HTML
 HTMLExport html = new HTMLExport();
 html.SinglePage = true; // Single page report
 html.Navigator = false; // Top navigation bar
 html.EmbedPictures = true; // Embeds images into a document
 report.Export(html, stream);
 mime = "text/" + query.Format; // Override mime for html
 }
 }
 }
 // Get the name of the resulting report file with the necessary extension var file = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format);
 // If the inline parameter is true, then open the report in the browser
 if (query.Inline)
 return File(stream.ToArray(), mime);
 else
 // Otherwise download the report file
 return File(stream.ToArray(), mime, file); // attachment
 }
 // Handle exceptions
 catch
 {
 return new NoContentResult();
 }
 finally
 {
 stream.Dispose();
 }
 }
 }
 else
 return NotFound();
 }

现在我们需要一个网页来显示报表。当然,您可以不使用它并在地址栏中输入URL。但是,使用现成的报表超链接将更加清晰。 让我们创建一个简单的html索引文档。将它放在wwwroot文件夹的根目录中。这是它的内容:

<!DOCTYPE html>
<html>
<head>
 <title>FastReport.Core Web Api</title>
 <meta charset="utf-8" />
</head>
<body>
 <h1>FastReport.Core Web Api</h1>
 <hr />
 <a href="/api/values/">List Of All Reports</a><br />
 <a href="/api/values/1?format=pdf">Get First Report in PDF</a><br />
 <a href="/api/values/1?format=html">Get First Report in HTML</a><br />
 <a href="/api/values/1?format=pdf&inline=true">Get First Report in PDF inline</a><br />
 <a href="/api/values/2?format=html&inline=true">Get Second Report in HTML inline</a><br />
 <a href="/api/values/1?format=pdf&inline=true&parameter=REPORT">Get First Report in PDF inline with Parameter=REPORT</a><br />
 <a href="/api/values/1?format=html&inline=true&parameter=REPORT">Get First Report in HTML inline with Parameter=REPORT</a><br />
</body>
</html>
 </html>

我们添加了7个超链接。第一个允许您显示可用报表的列表。第二个允许您下载PDF格式的索引为1的报表。第三个超链接允许您下载HTML格式的索引为1的报表。第四个 - 允许您在浏览器中以PDF格式打开索引为1的报表。第五个 - 允许您在浏览器中以HTML格式索引2打开报表。第六个 - 允许您在浏览器中以PDF格式打开索引为1的报表,并将参数值传送给它。第七个 - 允许您在浏览器中打开HTML格式的索引为1的报表,并将参数值传送给它。

当然,要在报表中显示参数的值,您需要将其添加到报表和报表页面。 但是,将index.html添加到根目录是不够的。为了在默认情况下打开此页面,您需要在启动设置中调整某些内容。打开Properties文件夹,即launchSettings.json文件。并删除两行:“launchUrl”:“api / values”。

要启用对静态页面和FastReport库的支持,请在Startup.cs中的Configure方法中添加几行:

app.UseFastReport();
 app.UseDefaultFiles();
 app.UseStaticFiles();

启动应用程序:

七个超链接的列表。让我们点击第一个:

报表列表以json格式显示。在.Net Core中,json完全取代了xml。事实是如此简洁和易懂。 单击第二个链接。浏览器以pdf格式下载报表:

单击第五个链接。浏览器将报表打开为html页面。

单击最后一个链接。报表也会在浏览器中打开,但请注意其标题。标题显示传递的参数的值 - REPORT。

因此,我们学习了如何使用FastReport.Core创建.Net Core Web API应用程序。

原文地址:https://www.cnblogs.com/wxchuachua/p/9999342.html

时间: 2024-08-29 20:59:26

如何在Web API应用程序中使用FastReport的相关文章

在docker中运行ASP.NET Core Web API应用程序

本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过程中,也会对docker的使用进行一些简单的描述.对于.NET Core以及docker的基本概念,网上已经有很多文章对其进行介绍了,因此本文不会再详细讲解这些内容.对.NET Core和docker不了解的朋友,建议首先查阅与这些技术相关的文档,然后再阅读本文. 先决条件 要完成本文所介绍的演练任务,需要准备以下环境: Visual Studio 2015,或者Vi

IIS8.5 布署 WEB API的程序时,遇到的问题

##IIS7/8 HTTP Error 500.19 错误 0x80070021  IIS7.0/8.0的错误HTTP Error 500.19 - Internal Server Error ,错误代码为0x80070021,大概原因为IIS7.0的安全设定相比前版本有很大的变更.IIS7.0的安全设置文件在%windir%\system32\inetsrv \config\applicationHost.config,这里定义所有Web程序的安全设置,在各个Web程序的web.config可

Web Api 2.0中使用Swagger生成Api文档的2个小Tips

当Web Api 2.0使用OAuth2授权时,如何在Swagger中添加Authorization请求头? Swagger说明文档支持手动调用Api, 但是当Api使用OAuth2授权时,由于没有地方可以输入授权Token, 导致响应结果一直是401没有授权. 解决方案: 在Swagger配置文件中,添加对请求头中Authorization的设置. 1. 在Api项目中添加一个新类AddAuthorizationHeader并实现IOperationFilter接口 public class

Asp.net mvc web api 在项目中的实际应用

Asp.net mvc web api 在项目中的实际应用 前言:以下只是记录本人在项目中的应用,而web api在数据传输方面有多种实现方式,具体可根据实际情况而定! 1:数据传输前的加密,以下用到 微软自带的 Rijndael 类(关于Rijndael 的更多信息请参见MSDN),32位密钥加16对称算法初始化向量,代码如下: //简单定义一个实体类: public class User { public int Id { get; set; } public string Name { g

如何用web api在网页中嵌入二维码?

如何用web api在网页中嵌入二维码? 随着智能手机和平板电脑的日益普及,二维码逐渐成了链接智能终端和传统网站的桥梁.在下文中,笔者将介绍几个实时生成二维码的web api,希望能够简化web design过程中的二维码集成工作. 1. 范例一 <img src="http://qrickit.com/api/qr?d=http://www.taobao.com" > 上述代码产生如下的二维码图片: 该web api还支持下面的这些特性, 说明文字:例如addtext=H

如何在web api中使用SignalR

说明: 在webapi中使用signalr,使用IIS 环境: vs2012, .net4.5 第一步:建web api项目 第二步:nuget导入signalr Install-Package Microsoft.AspNet.SignalR Install-Package Microsoft.Owin.Cors  (用于跨域) 第三步:创建hub类 demo是从网上down的,去除了一些没用到的东西,只保留了MessageHub 第四步:创建Startup类 第五步:在webapi方法中调用

[Solution] 使用Autofac在MVC、Web API、WCF中实现IOC

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 本来想聊一下面试过程的,1个星期面了6家,4家当场给offer,2家技术通过(1家没下文,1家复试).从中也学习到一些东西,先还是继续Coding吧. 官网:http://autofac.org/ 下载:Install-Package Auto

在docker中运行ASP.NET Core Web API应用程序(附AWS Windows Server 2016 widt Container实战案例)

环境准备 1.亚马逊EC2 Windows Server 2016 with Container 2.Visual Studio 2015 Enterprise(Profresianal要装Update 3) 3..NET Core 1.0.0 – VS 2015 Tooling Preview 2.请点击此处安装 4.Microsoft .NET Core SDK,可以到微软官方网站下载安装 实验步骤 一.Docker环境准备 亚马逊EC2 Windows Server 2016 with C

如何在MFC对话框应用程序中使用ColorPicker控件

在日常的应用程序开发中,当涉及到曲线绘制时,为了将多条不同类型的曲线区分开,常常需要将它们指定不同的颜色.今天在这里简单的记录一下,如何实现及使用ColorPicker控件.程序用到4个文件依次为:ColourPicker.cpp.ColourPicker.h.ColourPopup.cpp.ColourPopup.h.应用程序的执行效果如下图所示: 本实现过程通过在Button按钮中进行重绘.基于Visual Studio 2008的工程下载地址:位置一.位置二.