Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在web API中更改返回列表的格式?_C#_Asp.net_.net_Asp.net Web Api - Fatal编程技术网

C# 如何在web API中更改返回列表的格式?

C# 如何在web API中更改返回列表的格式?,c#,asp.net,.net,asp.net-web-api,C#,Asp.net,.net,Asp.net Web Api,我对WEB API相当陌生,所以请原谅我的无知。我试图返回一个特定用户将要参加的活动列表,仅此而已。我的代码可以工作,但它返回的信息比我需要的多。这是调用API时返回的:[{“$id”:“1”,“eventID”:“1”},{“$id”:“2”,“eventID”:“2”}] 我的控制器代码如下: public HttpResponseMessage Get(string id) { List<GetEventAttend> events = null; events

我对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);
}

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

您就快到了,但是您不需要选择新的
geteventattent
而只需选择
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);
}
geteventattent
类真的那么小吗,还是只是为了演示?如果它只是web api结果的容器,那么您就不需要该类,正如答案所示

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

在原始代码中,您可能已经配置了引用处理,请参阅关于如何禁用该功能:


您已经配置了引用处理。工作正常,谢谢!这将只选择“返回字符串列表”,当您希望在某个时候扩展响应时,这对可维护性是不利的。@CodeCaster注意到这一点,我冒昧地在回答中详细说明了这一点。
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);
}
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = 
Newtonsoft.Json.PreserveReferencesHandling.None;