在ASP.Net Core 2.0 Angular SPA中添加Telerik Reporting REST服务项目
刚好踩过类似的坑,给你整理了一套能跑通的配置流程,针对你用VS2017 + ASP.NET Core 2.0 Angular SPA + Telerik .NET 4.6.1 REST服务的场景:
核心配置步骤与排坑点
1. 跨域配置(重中之重)
你的SPA和REST服务是两个独立项目,跨域是第一个要解决的问题:
- 在.NET 4.6.1的REST服务项目中,安装
Microsoft.AspNet.CorsNuGet包 - 打开
WebApiConfig.cs,添加跨域规则(替换成你的SPA实际端口,比如默认4200):
public static void Register(HttpConfiguration config) { // 启用CORS,允许SPA域名的请求 var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*"); config.EnableCors(cors); // 保留原有路由配置 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
2. ReportsController路径验证
Telerik模板生成的控制器可能存在报表路径错误:
- 打开
ReportsController.cs,找到GetReportSource方法,用物理路径加载报表文件(假设报表放在服务项目的Reports文件夹):
var reportPath = HostingEnvironment.MapPath("~/Reports/YourTargetReport.trdp"); var reportSource = new UriReportSource { Uri = reportPath };
如果报表是嵌入资源,记得调整为EmbeddedResourceReportSource加载方式
3. ASP.NET Core SPA代理配置(开发/生产兼容)
为了避免生产环境跨域问题,推荐配置反向代理:
开发环境(Angular代理)
在Angular项目根目录创建proxy.conf.json:
{ "/api/reports/**": { "target": "http://localhost:5001", // 替换成你的REST服务端口 "secure": false, "changeOrigin": true } }
然后修改angular.json的启动命令,指定代理配置:
"scripts": { "start": "ng serve --proxy-config proxy.conf.json" }
生产环境(Core中间件)
在Core项目安装Microsoft.AspNetCore.Proxy NuGet包,然后在Startup.cs的Configure方法添加:
app.UseProxy(new ProxyOptions { Host = "http://localhost:5001" // REST服务地址 }); // 保留原有SPA配置 app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; });
4. 调试与运行注意事项
- 设置多启动项目:右键解决方案→属性→启动项目→选择「多启动项目」,把两个项目的操作都设为「启动」
- 固定REST服务端口:在.NET 4.6.1项目属性→Web→服务器,设置一个固定端口(比如5001),避免每次启动端口变化
- 验证服务可用性:直接访问
http://localhost:5001/api/reports,如果返回JSON格式的报表列表,说明REST服务配置正常
5. Angular客户端Viewer配置
确保Telerik Report Viewer指向正确的服务地址:
import { Component } from '@angular/core'; @Component({ selector: 'app-report-viewer', template: ` <telerik-report-viewer [serviceUrl]="'/api/reports'" [reportSource]="{ report: 'YourTargetReport.trdp' }" [viewMode]="'INTERACTIVE'" [scaleMode]="'FIT_PAGE'" ></telerik-report-viewer> ` }) export class ReportViewerComponent { }
内容的提问来源于stack exchange,提问作者TDC
相关产品推荐
相关产品推荐

