Web Api返回错误

时间:2017-08-09 07:15:31

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

我写了一个api来获取json格式的一些对象。它在Linq命令中获取值并转到return方法。但是没有回报我的期望。

select subscriber.id, 
count(text_alert.id) total_alerts_received, 
count(case when text_alert.create_date_time::date <= '2017-07-07' then 1 end) before_alerts_received,
count(case when text_alert.create_date_time::date > '2017-07-07' then 1 end) after_alerts_received
from subscriber
left join text_alert
on subscriber.id = text_alert.subscriber_id
where subscriber.sms = 0
group by subscriber.id

我搜索了很多,但还没有找到任何东西。

values return ({"Message": "An error has occurred."}) 

1 个答案:

答案 0 :(得分:3)

有两种方法可以做到这一点。

  1. 包含Json library,然后返回自定义json对象。只需在Json中传递orders列表并返回即可。
  2. return JsonConvert.SerializeObject(new jTableResponse(result), Formatting.None);

    OR

    return Json(yourobject, JsonRequestBehavior.AllowGet);

    1. 另一种选择是创建自己的响应模型,然后使用Json库将其作为Json对象返回。
    2. 以下是完整的示例。

      using System; 
      namespace MyProject.Api_Models
      {
          public class ApiResponse
          {
              public bool Status { get; set; }
              public Object Data { get; set; }
              public string Message { get; set; }
          }
      }
      

      用作:

      [HttpPost]
      public JsonResult GetGroupFriendsLists(int groupid)
      {
          var grp = db.Groups.Where(k => k.GroupId == groupid).Any();
          if (!grp)
          {
              return Json(new ApiResponse
              {
                  Message = "Invalid group inforamtion.",
                  Status = false
              }, JsonRequestBehavior.AllowGet);
          }
          var lists = db.Groups.Where(k => k.GroupId == groupid).Select(k => k.SharedLists).FirstOrDefault().Where(k => k.ListType == SharedListTypes.Friends && (k.ExpiryDate == null || k.ExpiryDate.Value.Date > DateTime.Now.Date)).Select(
              k =>
              new
              {
                  k.CreatorId,
                  ExpiryDate = HelperFunctions.DateTimeFormattedString(k.ExpiryDate),
                  k.ListId,
                  k.ListName,
                  k.ListType,
                  TimeStamp = HelperFunctions.DateTimeFormattedString(k.TimeStamp),
                  ItemsCount = k.ListItems.Count
              }).ToList();
          if (lists.Count <= 0)
          {
              return Json(new ApiResponse
              {
                  Status = false,
                  Message = "No friends lists in this group."
              }, JsonRequestBehavior.AllowGet);
          }
          return Json(new ApiResponse
          {
              Status = true,
              Message = "We found the friends shared lists of this group.",
              Data = lists
          }, JsonRequestBehavior.AllowGet);
      }
      

      你可以测试一下。