我正在构建一个仅 JSON 的 WepApi,并且我有一个返回列表的控制器。我用 Datacontract/Datamember 属性修饰了列表,如下所示:
[DataContract(Name = "Files", Namespace = "http://schemas.example.com")]
public class FileDesc
{
[DataMember(Name = "MyFileName")]
public string Name { get; set; }
[DataMember(Name = "MyFilePath")]
public string Path { get; set; }
[DataMember(Name = "MyFileSize")]
public long? Size { get; set; }
public FileDesc(string n, string p, long? s)
{
Name = n;
Path = p;
Size = s;
}
}
在我的控制器中,我返回这样的列表:
// Response
List<FileDesc> FileList = new List<FileDesc>();
foreach (MultipartFileData file in provider.FileData)
{
FileList.Add(new FileDesc(file.Headers.ContentDisposition.FileName, file.LocalFileName , file.Headers.ContentDisposition.Size ));
}
return FileList;
但在 JSON 输出中,列表的名称属性缺失:
[
{
"myFileName": "\"ArduinoUNO.png\"",
"myFilePath": "c:\\images\\ArduinoUNO.png",
"myFileSize": null
}
]
为了强制仅输出 JSON,我删除了 Global.asax 上的 xml 格式化程序:
//Only JSON
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
提前致谢