【问题标题】:How to change format of returned list in web API?如何更改 Web API 中返回列表的格式?
【发布时间】:2017-11-12 15:13:18
【问题描述】:

我对 WEB API 还很陌生,所以请原谅我的无知。我正在尝试返回特定用户将参加的活动列表,仅此而已。我的代码有效,但它返回的信息比我需要的多。这是我调用 API 时返回的内容: [{"$id":"1","eventID":"1"},{"$id":"2","eventID":"2"}]

我的控制器代码如下:

public HttpResponseMessage Get(string id)
{
    List<GetEventAttend> events = null;
    events = db.userattends.Where(x => x.userID == id).Select(s => new GetEventAttend()
    { eventID = s.eventID }).ToList<GetEventAttend>();

    return Request.CreateResponse(HttpStatusCode.OK, events);
}

这是 GetEventAttend 的代码:

public class GetEventAttend
{

    public string eventID { get; set; }
}

有什么方法可以返回 {"1","2"} 的格式?

【问题讨论】:

  • 您已配置参考处理。

标签: c# asp.net .net asp.net-web-api


【解决方案1】:

您就快到了,但您无需选择新的GetEventAttend,只需选择eventID 字段并返回这些字段:

public HttpResponseMessage Get(string id)
{
    var events = db.userattends.Where(x => x.userID == id).Select(s => s.eventID).ToList();

    return Request.CreateResponse(HttpStatusCode.OK, events);
}

GetEventAttend 类真的那么小还是只是为了演示目的?如果它只是 Web api 结果的容器,那么您不需要该类,如答案所示。

编辑:CodeCaster 有道理。这个答案将返回一个 eventIds 数组。现在这可能就足够了,但在以后的阶段中,您可能希望返回一个事件数组,即使它们仅包含标识符。因为现在如果您想包含有关事件的其他信息,您必须创建一个新的 api 或引入重大更改。

在原始代码中您可能已经配置了引用处理,请参阅the docs 了解如何禁用它:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
Newtonsoft.Json.PreserveReferencesHandling.None; 

【讨论】:

  • 完美运行,谢谢!
  • 这只会选择返回一个字符串列表,当您想在某个时候扩展响应时,这不利于可维护性。
  • @CodeCaster 点了,我冒昧地在我的回答中详细说明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 2020-07-26
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多