Skip to main content
 首页 » 编程设计

c#之如何在 WEB API 中格式化 HttpResponseMessage 中的列表

2024年02月05日26cloudgamer

在这里,我想要“用户”列表作为响应。但它也包含消息。我希望消息只打印一次。目前它正在打印 user.count 次。

for (int i = 0; i < user.Count; i++) 
 { 
   if (user[i].Message == "Success") 
      { 
        resp = new HttpResponseMessage { Content = new ObjectContent(typeof(List<GetUserList>), user, GlobalConfiguration.Configuration.Formatters.JsonFormatter) }; 
       } 
   else 
      { 
        resp = new HttpResponseMessage { Content = new StringContent("[{\"Message\":\"" + user[i].Message + "\"}]", System.Text.Encoding.UTF8, "application/json") }; 
       } 
 } 

结果应该是这样的:

{ 
  "message": " Successful", 
  "supervisorlist": [ 
  { 
    " userID ": "654", 
    " forename ": "John" 
  }, 
  { 
    " userID ": "655", 
    " forename ": "Jack" 
  } 
 ] 
 
} 

请您参考如下方法:

成功的例子

var responseObj = new { message = "Successful", supervisorlist = users }; 
 
resp = new HttpResponseMessage  
        {  
            Content = new StringContent(JsonConvert.SerializeObject(responseObj),  
                                            System.Text.Encoding.UTF8, "application/json")  
        };