2016-11-10 97 views
1

我做一些代码在我的网页API列表变量,我想列出一个模型类的所有变量,并告诉他们网页API - 一类

这里是Web API代码:

//Method to list all the variables from the class Hello 
    [HttpGet] 
    [Route("api/listOfVariables")] 
    public IEnumerable<String> listOfVariables() 
    { 
     return typeof(Hello).GetFields() 
            .Select(field => field.Name) 
            .ToList(); 
    } 

Model类

public class Hello 
    { 
     public int HelloId { get; set; } 

     public string name { get; set; } 
    } 
    } 

和Web API的配置:

 config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

当我使用以下网址: http://localhost:1861/api/listOfVariables

我得到这个信息:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance"   xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/> 

有人能帮助我吗?我是新来的.net

回答

1

Hello类没有任何字段,所以你看到的是一个空的列表。该类别具有属性。您可以使用GetProperties()来获取这些内容。

举例说明:

class Hello 
{ 
    public int HelloId; // field 
} 

class Hello 
{ 
    public int HelloId { get; set; } // property 
} 
+0

其正确。感谢您的解释和您的时间!我真的很感激。我会接受你的答案作为解决方案 – RtyUP