Web API通过JSON从文件夹返回文件列表 [英] Web API returning list of files from folder via JSON

查看:62
本文介绍了Web API通过JSON从文件夹返回文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取特定文件夹中jpg文件的列表,并将该列表通过json返回给有角度的引导轮播.如果我以json格式对文件列表进行硬编码并将其手动放置在作用域中,则角度引导程序部分将正常工作,但是我无法弄清楚如何从此Web api控制器以正确的格式返回数据.问题主要在于我相信的foreach循环.我已经尝试了使用@符号,双引号,单引号等各种方法.谢谢.

I am trying to get a list of the jpg files in a particular folder, and return that list via json to an angular bootstrap carousel. The angular bootstrap part works fine if I hard code the list of files in json format and manually put that on the scope, but I can not figure out how return the data in the proper format from this web api controller. The problem is mainly with the foreach loop I believe. I've tried various methods with the @ symbol, double quotes, single quotes, etc. I am definitely stuck at this point. Thank you.

[Route("api/GetIncidentPhotos/{Id}/Incidents")]
public IEnumerable<string> GetIncidentPhotos(int Id)
{ 
    List<string> files = new List<string>();
    DirectoryInfo dirInfo = new DirectoryInfo(@"C:\SecurityManager\Photos\3\");

    foreach (FileInfo fInfo in dirInfo.GetFiles())
    {
        files.Add("{ 'path:' + '\\Photos\\3\\' + fInfo.Name + '}' ");            
    }

    return files.ToList();

}

这是html/bootstrap/angular标记,它使用从API调用返回的文件列表来构建图像轮播.

Here is the html/bootstrap/angular markup that uses the list of files returned from the API call to build the image carousel.

<div class="carousel-inner">
    <div class="item" ng-class="{active:!$index}" ng-repeat="photo in photoPath">            
        <img src="{{ photo.path }}" class="img-responsive" style="border: solid 1px;">
    </div>
</div>

推荐答案

首先,对路径对象使用模型类,这样您就不必依靠手工序列化为JSON.

First of all, use a model class for your path objects so you don't have to rely on serializing to JSON by hand.

 [Route("api/GetIncidentPhotos/{Id}/Incidents")]
    public IEnumerable<FilePath> GetIncidentPhotos(int Id)
    {
        List<FilePath> files = new List<FilePath>();
        DirectoryInfo dirInfo = new DirectoryInfo(@"C:\SecurityManager\Photos\3\");

        foreach (FileInfo fInfo in dirInfo.GetFiles())
        {
            files.Add(new FilePath(){ path = @"\Photos\3\" + fInfo.Name});      
        }

        return files.ToList();
    }
    public class FilePath
    {
        public string path { get; set; }
    }

这篇关于Web API通过JSON从文件夹返回文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆