0

对于我们的客户,我们有一个返回 PDF 文件的 MVC 操作。以下代码是返回 FileResult 的逻辑。

public FileResult DownloadAbsFile(string id)
{
    String path = GetPathNameByID(id);
    if (System.IO.File.Exists(path))
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(path);
        string fileName = System.IO.Path.GetFileName(path);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
    }
    else
    {
        return null;
    }
}

当我大多数时候使用正确的 URL 请求 PDF 文件时,没有问题。但是,某些用户会收到错误消息。这个错误让我困惑了很长一段时间。我得到的错误如下。

Exception type: NullReferenceException 
Exception message: Object reference not set to an instance of an object
at ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in 
xxx\Views\Shared\SiteLayout.cshtml:line xxx
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext 
pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.<>c__DisplayClass3.
<RenderPageCore>b__2(TextWriter writer)
at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, 
Action`1 body)
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext 
pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter 
writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, 
TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at 
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext 
controllerContext, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.
<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at 

在 cshtml 中的特定行上,它尝试访问未设置的 ViewBag 中的 PageTitle。这个值永远不会设置,所以我明白了。但我不明白的是为什么它首先尝试渲染视图。

有人可以帮我吗?

4

0 回答 0