SiteLayout.cshtml中的NullReferenceException与FileResult

时间:2017-09-01 08:50:51

标签: asp.net-mvc razor fileresult

对于我们的客户,我们有一个返回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。这个值永远不会设置,所以我明白了。但我没有得到的是为什么它首先尝试渲染视图。

有人可以帮我吗?

0 个答案:

没有答案