找不到文件时处理FileContentResult

我有一个控制器操作,根据容器引用名称(即blob中文件的完整路径名称)从azure blob下载文件。 代码看起来像这样:

public FileContentResult GetDocument(String pathName) { try { Byte[] buffer = BlobStorage.DownloadFile(pathName); FileContentResult result = new FileContentResult(buffer, "PDF"); String[] folders = pathName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // get the last one as actual "file name" based on some convention result.FileDownloadName = folders[folders.Length - 1]; return result; } catch (Exception ex) { // log error } // how to handle if file is not found? return new FileContentResult(new byte[] { }, "PDF"); } 

BlobStorage类有我的助手类从blob下载流。

我的问题在代码注释中说明:当找不到文件/流时,我应该如何处理场景? 目前,我传递的是一个空的PDF文件,我觉得这不是最好的方法。

处理Web应用程序中未找到的正确方法是将404 HTTP状态代码返回给客户端,在ASP.NET MVC术语中将其转换为从控制器操作返回HttpNotFoundResult :

 return new HttpNotFoundResult(); 

啊,oops,没注意到你还在使用ASP.NET MVC 2.你可以自己实现它,因为HttpNotFoundResult仅在ASP.NET MVC 3中引入:

 public class HttpNotFoundResult : ActionResult { public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } context.HttpContext.Response.StatusCode = 404; } }