[英]Handling FileContentResult when file is not found
I have a controller action that downloads a file from an azure blob based on the container reference name (ie full path name of the file in the blob). 我有一个控制器操作,根据容器引用名称(即blob中文件的完整路径名称)从azure blob下载文件。 The code looks something like this:
代码看起来像这样:
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");
}
The BlobStorage
class there is my helper class to download the stream from the blob. BlobStorage
类有我的助手类从blob下载流。
My question is stated in the code comment: How should I handle the scenario when the file/stream is not found? 我的问题在代码注释中说明:当找不到文件/流时,我应该如何处理场景? Currently, I am passing an empty PDF file, which I feel is not the best way to do it.
目前,我传递的是一个空的PDF文件,我觉得这不是最好的方法。
The correct way to handle a not found in a web application is by returning a 404 HTTP status code to the client which in ASP.NET MVC terms translates into returning a HttpNotFoundResult from your controller action: 处理Web应用程序中未找到的正确方法是将404 HTTP状态代码返回给客户端,在ASP.NET MVC术语中将其转换为从控制器操作返回HttpNotFoundResult :
return new HttpNotFoundResult();
Ahh, oops, didn't notice you were still on ASP.NET MVC 2. You could implement it yourself because HttpNotFoundResult
was introduced only in ASP.NET MVC 3: 啊,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;
}
}
NotFound()
NotFound()
Your controller must inherit of Controller
and the method must return ActionResult
您的控制器必须继承
Controller
并且该方法必须返回ActionResult
Example: 例:
public ActionResult GetFile(string path)
{
if (!File.Exists(path))
{
return NotFound();
}
return new FileContentResult(File.ReadAllBytes(path), "application/octet-stream");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.