Как получить список файлов из папки через WebApi?

Подскажите пожалуйста, как реализовать метод WebApi, который бы вернул мне список файлов из папки, но в JSON ответе путь к файлам был бы по типу http://localhost:5000/file1.txt,http://localhost:5000/file2.txt. Первое что пришло в голову это

[HttpGet]
    public IEnumerable<string> Get()
    {
        return Directory.GetFiles(@"D:\DIR-300NRUrevBx").ToList();
        //Тут у меня в параметрах нужная мне папка.

    }

Но получаю в ответ такое. введите сюда описание изображения Каким образом мне получить пути к файлам с учетом сайта?


Ответы (2 шт):

Автор решения: Lets Drum

Варварское решение


[HttpGet]
public string Get()
{
    var path = @"D:\DIR-300NRUrevBx";
    string[] files = Directory.GetFiles(path);

    var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/";

    return JsonConvert.SerializeObject(files.ToList()
        .Select(x => x.Replace(path + "\\", ""))
        .Select(x => baseUrl + x));
}

Результат (где path = @"D:\Downloads"):

[ 
   "http://localhost:63564/Adobe Illustrator.exe",
   "http://localhost:63564/code-carbon.png",
   "http://localhost:63564/Erik_Frimen_Elizabet_Frimen_-_Patterny_Proektirovania_Head_First_O_39_Reilly_-_2011.pdf",
   "http://localhost:63564/jenkins-2.204.1.zip",
   "http://localhost:63564/Martin_Fauler_-_Shablony_Korporativnykh_Prilozheniy.pdf"
]
→ Ссылка
Автор решения: Bulson

Не могу понять только зачем такое нужно кому-то.

[HttpGet]
    public IEnumerable<string> Get()
    {
        var hostAddress = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
        return GetFileList(hostAddress, @"D:\images");
    }

    private IEnumerable<string> GetFileList(string hostAddress, string path)
    {
        List<string> resut = new List<string>();
        foreach (var fi in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
        {
            var fileName = Path.GetFileName(fi);
            resut.Add($"{hostAddress}/{fileName}");
        }

        return resut;
    }
→ Ссылка