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

在Blazor Server中使用Rotativa ViewAsPdf遇空引用异常求助

在Blazor Server中使用Rotativa.AspNetCore生成PDF的解决方案

针对你遇到的“对象引用未设置到对象的实例”异常,以下是几个经过验证的解决步骤:

1. 启用MVC视图服务

Blazor Server项目默认未完整配置MVC视图相关服务,需在Program.cs中补充注册:

builder.Services.AddControllersWithViews(); // 添加控制器与视图支持

同时在中间件部分添加控制器路由映射:

app.MapControllers(); // 确保ExportPDF接口可被正常访问

2. 修正Rotativa配置路径

RotativaConfiguration.Setup需传入wwwroot绝对路径,调整Program.cs中的配置代码:

var webRootPath = app.Environment.WebRootPath;
RotativaConfiguration.Setup(webRootPath);
app.UseRotativa();

另外需确认wkhtmltopdf的对应平台版本(如Windows的wkhtmltopdf.exe)已放置在wwwroot/Rotativa目录下,若路径自定义可直接传入对应路径:

RotativaConfiguration.Setup(@"C:\YourProject\Rotativa");

3. 检查视图与模型绑定

  • 确认PDF.cshtml路径无误,且视图中未引用未初始化的对象(比如使用Model时需确保模型已正确传递)。
  • 验证PDFModel绑定逻辑,确保HttpClient POST请求时,模型数据被正确序列化并传递到控制器。

4. 修复CustomSwitches语法错误

原配置中存在引号转义错误,会导致wkhtmltopdf解析失败引发空引用,修正为:

CustomSwitches = "--footer-center \"MyDocument\" --footer-right \"Page: [page]/[toPage]\" --footer-font-size \"6\""

5. 优化控制器返回逻辑

将返回类型改为IActionResult,并添加模型校验与完整的页边距配置:

[HttpPost("exportPDF")]
public IActionResult ExportPDF([FromBody] PDFModel model)
{
    if (model == null)
    {
        return BadRequest("模型数据为空");
    }
    
    return new ViewAsPdf("~/Views/MyView/PDF.cshtml", model)
    {
        FileName = $"MyFile{DateTime.Now:yyyyMMddHHmmss}.pdf",
        PageSize = Rotativa.AspNetCore.Options.Size.A4,
        PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
        PageMargins = { Left = 15, Right = 15, Top = 15, Bottom = 15 },
        CustomSwitches = "--footer-center \"MyDocument\" --footer-right \"Page: [page]/[toPage]\" --footer-font-size \"6\""
    };
}

6. 调整Blazor组件的HttpClient调用

确保组件中正确设置请求内容类型,并通过JS实现PDF下载:

private async Task ExportToPdf()
{
    var model = new PDFModel { /* 填充模型数据 */ };
    var json = JsonSerializer.Serialize(model);
    var content = new StringContent(json, Encoding.UTF8, "application/json");
    
    var response = await HttpClient.PostAsync("/exportPDF", content);
    if (response.IsSuccessStatusCode)
    {
        var bytes = await response.Content.ReadAsByteArrayAsync();
        await JS.InvokeVoidAsync("downloadFile", $"MyFile{DateTime.Now:yyyyMMddHHmmss}.pdf", bytes);
    }
}

在_Host.cshtml中添加下载用JS函数:

function downloadFile(filename, byteArray) {
    var blob = new Blob([byteArray], { type: 'application/pdf' });
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

经过以上步骤,已有不少开发者成功在Blazor Server中实现Rotativa生成PDF的功能,核心是确保MVC视图服务配置完整、Rotativa路径正确、视图与模型无空引用,以及命令行参数语法合规。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:46:21