2016-11-10 98 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