You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Blazor应用中的ShowPdf中间件添加授权验证?

解决方案

方案一:给现有中间件添加授权验证

无需改动现有中间件结构,直接在逻辑开头加入身份与角色校验,同时确保中间件在认证授权之后注册:

  1. 修改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);
}
  1. 确保Startup.cs中中间件注册顺序正确:
// 先注册认证与授权中间件
app.UseAuthentication();
app.UseAuthorization();

// 再注册ShowPdf中间件
app.UseShowPdf();

方案二:替换为Razor页面(解决你遇到的报错问题)

你之前改成Razor页面后报错,是因为还在调用已不存在的UseShowPdf()中间件,按以下步骤调整:

  1. 创建ShowPdf.cshtml Razor页面,添加授权属性并实现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);
        }
    }
}
  1. 在Startup.cs中删除appBranch.UseShowPdf();调用,同时确保已注册IReportData服务:
services.AddScoped<IReportData, ReportData>();
  1. 修改前端跳转地址:
// 原地址:"/ShowPdf.mdwr?reportid=" + report.Report
// 改为Razor页面路由:
NavigateToNewTab("/ShowPdf?reportid=" + report.Report);

额外建议

  • 避免直接new ReportData(),改用依赖注入提升代码可测试性与灵活性
  • 对reportid参数做合法性校验(比如是否为正整数),避免潜在的异常

内容的提问来源于stack exchange,提问作者Wolfgang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:27:55