NullReferenceException in SiteLayout.cshtml with FileResult

94 Views Asked by At

For a client of ours we have an MVC action which returns PDF files. The following code is the logic to return the 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;
    }
}

When I request a PDF file using the right URL most of the time there is no problem. However certain users get an error. The error is puzzling me for quite some time. The error I get is as follows.

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 

On the specific line in the cshtml it tries to access the PageTitle in the ViewBag, which wasn't set. This value is never set, so I get this. But what I do not get is why it is trying to render the view in the first place.

Can anybody help me with this?

0

There are 0 best solutions below