Processing FileContentResult when a file is not found

I have a controller action that loads a file from azure blob based on the name of the container reference (i.e. the full path name of the file in the 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"); } 

In the BlobStorage class, BlobStorage is my helper class for loading a stream from a blob.

My question is indicated in the code comment: How do I handle a script when a file / stream is not found? I am currently transferring an empty PDF file which, in my opinion, is not the best way to do this.

+9
c # asp.net-mvc-2 azure-storage-blobs filecontentresult
source share
2 answers

The correct way to handle the data not found in the web application is to return the 404 HTTP status code to the client, which under ASP.NET MVC conditions will be converted to return HttpNotFoundResult from the action of your controller:

 return new HttpNotFoundResult(); 

Ahh, oops, didn’t notice that you are still on ASP.NET MVC 2. You could implement it yourself, because HttpNotFoundResult was introduced only in 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; } } 
+19
source share

In ASP.NET Core use NotFound()

Your controller should inherit Controller and the method should return ActionResult

Example:

 public ActionResult GetFile(string path) { if (!File.Exists(path)) { return NotFound(); } return new FileContentResult(File.ReadAllBytes(path), "application/octet-stream"); } 
0
source share

All Articles