首页 > 解决方案 > 从文件夹下载的文件包括 .NET Core 上的 %2F 字符

问题描述

这一定是个愚蠢的问题。我在 c# 上有一个 Web API Rest,它有一个端点来生成和下载一个 excel 文件。我使用 NPOI 库。

如果文件是在我网站的根目录中生成的,它工作正常。但是当我尝试将文件移动到文件夹时,文件名包括文件夹和 de %2F 字符。我想这是一个 URL 编码问题,但不知道如何解决它。这是我的代码。

[AllowAnonymous]
    [HttpGet("ExportExcel")]
    public async Task<IActionResult> ExportExcel(int activos = 1, int idarticulo = -1, string filtro = "", string ordenar = "", int ordenarsentido = 1)
    {
        var memory = new MemoryStream();
        var newFile = @"Export/Articulos.xlsx";

        //IArticulosService articulosService = new ArticulosService(_validation.sConnectionString, _validation.sEmpresa);
        var mycon = _validation.GetConnectionStringFromClientID("ClientId1");
        IArticulosService articulosService = new ArticulosService(mycon, "Ciatema");

        try
        {
            // Genero el excel con el listado
            articulosService.ExportarExcel(newFile, activos, filtro, ordenar, ordenarsentido);
            using (var stream = new FileStream(newFile, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", newFile);
        }
        catch (QueryFormatException ex)
        {
            return BadRequest(ex.Message);
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
            return StatusCode(StatusCodes.Status500InternalServerError);
        }
    }

Donwload 文件名是:Export%2FArticulos.xlsx当我需要它时它只是Articulos.xlsx。谢谢!

标签: api.net-core

解决方案


您应该在返回 File 方法中仅传递文件名而不是完整路径,如下所示

  return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(newFile));

推荐阅读