如何为Blazor应用中的ShowPdf中间件添加授权验证?
解决方案
方案一:给现有中间件添加授权验证
无需改动现有中间件结构,直接在逻辑开头加入身份与角色校验,同时确保中间件在认证授权之后注册:
- 修改
ShowPdf中间件的Invoke方法:
public async Task Invoke(HttpContext context) { // 先校验用户身份与角色 if (!context.User.Identity.IsAuthenticated || !(context.User.IsInRole("User") || context.User.IsInRole("Admin") || context.User.IsInRole("Finance"))) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("未授权访问"); return; } // 原有PDF输出逻辑保留 this.pdfdb = new ReportData(); myReport = pdfdb.GetWithReport(Convert.ToInt32(context.Request.Query["reportid"])); byte[] reportBytes = myReport.ReportDocument; context.Response.ContentType = myReport.DocumentType; context.Response.Headers.Add("Content-Disposition", "attachment; " + "filename=\"iTraxReportDoc." + myReport.DocumentType +"\"; " + "size=" + reportBytes.Length + "; " + "creation-date=" + DateTime.Now.ToString("R").Replace(",", "") + "; " + "modification-date=" + DateTime.Now.ToString("R").Replace(",", "") + "; " + "read-date=" + DateTime.Now.ToString("R").Replace(",", "")); await context.Response.Body.WriteAsync(reportBytes); }
- 确保
Startup.cs中中间件注册顺序正确:
// 先注册认证与授权中间件 app.UseAuthentication(); app.UseAuthorization(); // 再注册ShowPdf中间件 app.UseShowPdf();
方案二:替换为Razor页面(解决你遇到的报错问题)
你之前改成Razor页面后报错,是因为还在调用已不存在的UseShowPdf()中间件,按以下步骤调整:
- 创建
ShowPdf.cshtmlRazor页面,添加授权属性并实现PDF输出:
@page "/ShowPdf" @attribute [Authorize(Roles = "User, Admin, Finance")] @model MyApp.ShowPdfModel
对应的PageModel:
namespace MyApp { public class ShowPdfModel : PageModel { private readonly IReportData _pdfdb; // 建议通过依赖注入获取,而非直接new // 构造函数注入IReportData(需先在Startup.cs注册该服务) public ShowPdfModel(IReportData pdfdb) { _pdfdb = pdfdb; } public async Task OnGet(int reportid) { var myReport = _pdfdb.GetWithReport(reportid); byte[] reportBytes = myReport.ReportDocument; Response.ContentType = myReport.DocumentType; Response.Headers.Add("Content-Disposition", $"attachment; filename=\"iTraxReportDoc.{myReport.DocumentType}\"; size={reportBytes.Length}; creation-date={DateTime.Now.ToString("R").Replace(",", "")}; modification-date={DateTime.Now.ToString("R").Replace(",", "")}; read-date={DateTime.Now.ToString("R").Replace(",", "")}"); await Response.Body.WriteAsync(reportBytes); } } }
- 在
Startup.cs中删除appBranch.UseShowPdf();调用,同时确保已注册IReportData服务:
services.AddScoped<IReportData, ReportData>();
- 修改前端跳转地址:
// 原地址:"/ShowPdf.mdwr?reportid=" + report.Report // 改为Razor页面路由: NavigateToNewTab("/ShowPdf?reportid=" + report.Report);
额外建议
- 避免直接
new ReportData(),改用依赖注入提升代码可测试性与灵活性 - 对
reportid参数做合法性校验(比如是否为正整数),避免潜在的异常
内容的提问来源于stack exchange,提问作者Wolfgang
相关产品推荐
相关产品推荐

