找不到文件时处理 FileContentResult

发布于 2024-11-16 16:12:51 字数 848 浏览 3 评论 0原文

我有一个控制器操作,它根据容器引用名称(即 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 文件,我认为这不是最好的方法。

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

The BlobStorage class there is my helper class to download the stream from the 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疧_╮線 2024-11-23 16:12:51

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

return new HttpNotFoundResult();

啊,哎呀,没有注意到您仍在 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;
    }
}

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:

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:

public class HttpNotFoundResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        context.HttpContext.Response.StatusCode = 404;
    }
}
莫言歌 2024-11-23 16:12:51

在 ASP.NET Core 中,使用 NotFound()

您的控制器必须继承 Controller 并且该方法必须返回 ActionResult

示例:

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

注意:上面的代码不会处理所有文件操作错误的情况,如路径中的无效字符或文件不可用(因为它超出了当前答案的范围)和正确的响应(例如由于权限或限制文件访问否则)

In ASP.NET Core, use NotFound()

Your controller must inherit of Controller and the method must return ActionResult

Example:

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

Note: the above code doesn't handle all cases of file operations errors as invalid chars in path or file unavailability (because it is beyond the scope of the current answer) and proper responses (like restricted file access due to permissions or else)

萌面超妹 2024-11-23 16:12:51

使用 ASP.NET Core 中的 CQRS 模式,您可以返回 NoContentResult。

public override async Task<ActionResult> Handle(GetProfileImageQuery request, CancellationToken cancellationToken)
{
    var item = await _mediaProfileImageRepository.GetByUserIdAsNoTracking(request.UserId, cancellationToken);
    if (item is null)
    {
        return new NoContentResult();
    }
    var fileContents = await File.ReadAllBytesAsync(item.FilePath, cancellationToken);

    return new FileContentResult(fileContents, item.ContentType)
    {
        LastModified = item.ModifiedAt,
        FileDownloadName = item.OriginalFileName
    };
}

Using the CQRS pattern in ASP.NET Core, you can return NoContentResult.

public override async Task<ActionResult> Handle(GetProfileImageQuery request, CancellationToken cancellationToken)
{
    var item = await _mediaProfileImageRepository.GetByUserIdAsNoTracking(request.UserId, cancellationToken);
    if (item is null)
    {
        return new NoContentResult();
    }
    var fileContents = await File.ReadAllBytesAsync(item.FilePath, cancellationToken);

    return new FileContentResult(fileContents, item.ContentType)
    {
        LastModified = item.ModifiedAt,
        FileDownloadName = item.OriginalFileName
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文