简体   繁体   中英

Web API JSON web service to show folder file information

I am relatively new to C# and trying to create a Web API web service that returns the contents of a folder on the web server in JSON format.

Here is my Fileinformation.cs class:

[DataContract]
public class FileInformation
{
    public FileInformation(string name, string mimeType, long size, DateTime lastModified)
    {
        this.name = name;
        this.mimeType = mimeType;
        this.size = size;
        this.lastModified = lastModified;
    }

    public string name { get; set; }
    [JsonProperty(PropertyName = "mime-type")]
    public string mimeType { get; set; }
    public DateTime lastModified { get; set; }
    public long size { get; set; }
}

Here is my Controller:

 public class ValuesController : ApiController
{
    // GET api/values
    public List<FileInformation> Get()
    {
        string ImageryFolder = @WebConfigurationManager.AppSettings["folderName"];
        string fileExtension = WebConfigurationManager.AppSettings["fileExtension"];

        DirectoryInfo d = new DirectoryInfo(ImageryFolder);
        FileInfo[] Files = d.GetFiles("*."+ fileExtension);
        var list = new List<FileInformation>();
        foreach (FileInfo fileInfo in Files)
        {
            string name = ImageryFolder + "\\" + fileInfo.Name;
            Debug.WriteLine(name);
            string mimeType = MimeMapping.GetMimeMapping(fileInfo.Name);
            long size = fileInfo.Length;
            DateTime lastModified = fileInfo.LastWriteTime;
            FileInformation newFile = new FileInformation(name, mimeType, size, lastModified);

            list.Add(newFile);
        }
        //var jsonResult = JsonConvert.SerializeObject(list);
        return list;
    }
}

The output I am currently getting looks like this, it is close because there are 8 files in the folder which is the same number of FileInformation nodes it is returning:

输出量

Data contract serialization is opt in. From the docs :

Apply the DataContractAttribute attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the DataContractSerializer.

You must also apply the DataMemberAttribute to any field, property, or event that holds values you want to serialize. By applying the DataContractAttribute, you explicitly enable the DataContractSerializer to serialize and deserialize the data.

And, while more recent versions of asp.net-web-api use Json.NET for JSON serialization, Json.NET respects data contract attributes .

Mark your properties with [DataMember] or switch to an opt-out serialization model .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM