原創|使用教程|編輯:我只采一朵|2018-01-10 09:54:43.000|閱讀 1954 次
概述:Web API使你可以快速輕松地創建HTTP服務。與常規的ASP.Net MVC項目不同,Web API不適用于視圖。要使用一種特殊類型的控制器,即返回模型對象的方法。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Web API使你可以快速輕松地創建HTTP服務。與常規的ASP.Net MVC項目不同,Web API不適用于視圖。要使用一種特殊類型的控制器,即返回模型對象的方法。
這種控制器的任務是傳輸數據,而不是表示。我們來看看如何創建一個提供FastReport報表的簡單Web服務。
一、首先,我們將創建并顯示兩個報表。
簡單的列表報表模板如下所示:
請注意,報表標題具有[Parameter]參數。你需要添加具有該名稱的報表參數。此報表的數據可以從演示數據庫nwind.xml的Employee表中獲取,具體位置 - C: \ Program Files (x86) \ FastReports \ FastReport.Net \ Demos \ Reports。
第二個報表模板將不包含數據。你可以從文件夾C:\ Program Files(x86)\ FastReports \ FastReport.Net \ Demos \ Reports中獲取現成的模板Barcodes.frx。
如上所述,我們將在我們的項目中使用兩個報表和一個數據庫。將它們添加到文件夾App_Data。在解決方案的瀏覽器中右鍵單擊該文件夾。選擇”添加” - >”現有項目”。像這樣,我們添加三個文件:Barcode.frx、Simple List.frx、nwind.xml?;蛘?,你可以簡單地用鼠標將這些文件拖動到App_Data文件夾。
二、創建一個ASP.NET應用程序:
單擊確定,然后轉到項目類型選擇:
選擇空模板。在底部標記MVC和Web API選項。如果你選擇一個Web API模板,你將收到一個充滿演示數據的項目。
三、在引用中添加一個鏈接到FastReport.dll庫。
四、現在,你需要添加一個數據模型。
為此,請在解決方案瀏覽器中選擇“模型”文件夾并右鍵單擊。在上下文菜單中,選擇Add-> Class:
將該類命名為Reports.cs。默認的類類型是“Class”。點擊“添加”。
在創建的類中,使用get
和set
方法添加兩個變量:
namespace FastReportWebApiDemo.Models { public class Reports { // Report ID public int Id { get; set; } // Report File Name public string ReportName { get; set; } } }
五、現在將控制器添加到項目中。
在Controllers文件夾上單擊右鍵。從上下文菜單中選擇Add-> Controller。
選擇控制器模板 - Web API2 Controller - Empty:
命名為ReportsController:
我們繼續編碼控制器中的邏輯。其任務是在瀏覽器中提供下載或以其中一種導出格式顯示報表:PDF、HTML、png。
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using FastReport; using FastReport.Export.Image; using FastReport.Export.Html; using FastReport.Export.Pdf; using FastReport.Utils; using FastReportWebApiDemo.Models; using System.Web.Hosting; using System.Data; using System.IO; using System.Net.Http.Headers; namespace FastReportWebApiDemo.Controllers { // The class of parameters in the query public class ReportQuery { // Format of resulting report: png, pdf, html public string Format { get; set; } // Value of "Parameter" variable in report public string Parameter { get; set; } // Enable Inline preview in browser (generates "inline" or "attachment") public bool Inline { get; set; } } public class ReportsController : ApiController { // Reports list Reports[] reportItems = new Reports[] { new Reports { Id = 1, ReportName = "Simple List.frx" }, new Reports { Id = 2, ReportName = "Barcode.frx" } }; // Get reports list public IEnumerable<Reports> GetAllReports() { return reportItems; } // Get report on ID from request public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query) { // Find report Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem != null) { string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName); string dataPath = HostingEnvironment.MapPath("~/App_Data/nwind-employees.xml"); MemoryStream stream = new MemoryStream(); try { using (DataSet dataSet = new DataSet()) { //Fill data source dataSet.ReadXml(dataPath); //Enable web mode Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); //Load report report.RegisterData(dataSet, "NorthWind"); //Register Data in report if (query.Parameter != null) { report.SetParameterValue("Parameter", query.Parameter); // Set the value of the parameter in the report. The value we take from the URL } // Two phases of preparation to exclude the display of any dialogs report.PreparePhase1(); report.PreparePhase2(); if (query.Format == "pdf") { //Export in PDF PDFExport pdf = new PDFExport(); // We use the flow to store the report, so as not to produce files report.Export(pdf, stream); } else if (query.Format == "html") { // Export in HTML HTMLExport html = new HTMLExport(); html.SinglePage = true; html.Navigator = false; html.EmbedPictures = true; report.Export(html, stream); } else { // Export in picture ImageExport img = new ImageExport(); img.ImageFormat = ImageExportFormat.Png; img.SeparateFiles = false; img.ResolutionX = 96; img.ResolutionY = 96; report.Export(img, stream); query.Format = "png"; } } } // Create result variable HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.ToArray()) }; stream.Dispose(); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment") { // Specify the file extension depending on the type of export FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format) }; // Determine the type of content for the browser result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + query.Format); return result; } // We handle exceptions catch { return new HttpResponseMessage(HttpStatusCode.InternalServerError); } } else return new HttpResponseMessage(HttpStatusCode.NotFound); } } }
如你所見,我們增加了另一個類到控制器。ReportQuery類定義了HTTP請求參數。這是格式,參數和內聯。第一個決定報表導出的格式,第二個決定報表中的參數值,第三個決定報表是否直接在瀏覽器中打開。
在ReportsController類中,我們創建了一個報表數組和兩個方法。名稱和報表標識符在數組中定義。第一個方法 GetAllReports ()
返回可用報表的列表。在我們的案例中,有兩個報表。第二種方法 GetReportById (int id, [FromUri] ReportQuery query)
返回標識符的報表。從查詢屬性中,我們可以得到參數格式、內聯和參數。它們分別定義:報表的導出格式、報表是否會直接在瀏覽器中打開,要發送到報表的參數的值。
六、在報表中添加一個網頁。
有了它,我們將用必要的參數向服務器發送請求。為此,請右鍵單擊項目名稱。選擇Add-> HTML Page:
設置名稱 - Index:
我們將下面的代碼添加到頁面中:
<!DOCTYPE html> <html> <head> <title>FastReport.Net Web Api Demo</title> <meta charset="utf-8" /> </head> <body> <h1>FastReport.Net Web Api Demo</h1> <hr /> <a href="/api/reports/">List Of All Reports</a><br /> <a href="/api/reports/1">Get First Report</a><br /> <a href="/api/reports/2">Get Second Report</a><br /> <a href="/api/reports/1?format=pdf">Get First Report in PDF</a><br /> <a href="/api/reports/2?format=html">Get Second Report in HTML</a><br /> <a href="/api/reports/1?format=pdf&inline=true">Get First Report in PDF inline</a><br /> <a href="/api/reports/2?format=html&inline=true">Get Second Report in HTML inline</a><br /> <a href="/api/reports/1?format=pdf&inline=true?meter=REPORT">Get First Report in PDF inline with Parameter=REPORT</a><br /> <a href="/api/reports/1?format=html&inline=true?meter=REPORT">Get First Report in HTML inline with Parameter=REPORT</a><br /> </body> </html>
從標題可以看出,我們可以:
七、從文件夾App_Start打開文件WebApiConfig.cs。為Index頁面添加一個MapHttpRoute:
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "Index", routeTemplate: "{id}.html", defaults: new { id = "index" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
在同一個文件夾中,找到RouteConfig.cs文件。它可能被刪除。
八、最后一步。打開文件Global.asax。刪除該行:
RouteConfig.RegisterRoutes(RouteTable.Routes);
現在路由只能通過WebApiConfig來完成。
九、運行應用程序。在瀏覽器中,我們看到命令列表:
以上。在WebAPI中使用FastReport并不比普通的ASP.Net MVC項目更困難。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn