MVC Web Api在C#中传递一个对象

时间:2012-11-27 14:06:40

标签: asp.net-mvc json asp.net-web-api

我需要在我的mvc webapi上找到一个来自和过去的日期,以便在这些日期之间检索项目。这是我最喜欢的事情,但我没试过(我尝试了几件事)。

我有一个在项目之间共享的对象:

public class SchedulerDateSpan
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

这是我的get控制器类:

public IEnumerable<Appointment> GetAppointments(SchedulerDateSpan dates)
{
   IEnumerable<Appointment> appointments =
   db.Appointments.Where(
   a =>
   (a.StartDate <= dates.StartDate && a.EndDate >= dates.StartDate) || (a.StartDate <= dates.EndDate && a.EndDate >= dates.EndDate) ||
   (a.StartDate > dates.StartDate && a.EndDate < dates.EndDate)).AsEnumerable();
   return appointments;
}

以下是来自客户的电话,其中日期类型为SchedulerDateSpan:

var client = new HttpClient { BaseAddress = new Uri(Properties.Settings.Default.SchedulerWebApi) };

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage resp = client.GetAsync(String.Format("api/Appointments/{0}",dates)).Result;

if (resp.IsSuccessStatusCode)
{ 
   var appointments = resp.Content.ReadAsAsync<IEnumerable<Appointment>>().Result;
          ......
}

我也尝试将其更改为看似有效的放置,但后来我无法使用Content.ReadAsAsync解析结果

感谢任何建议

2 个答案:

答案 0 :(得分:6)

默认情况下,复杂类型(例如SchedulerDateSpan)应在请求正文中传递。如果要从URI传递值,则必须将action参数标记为[FromUri]:

public IEnumerable<Appointment> GetAppointments([FromUri]SchedulerDateSpan dates)
{...}

然后,您可以从Uri中的查询字符串传递“日期”,如下所示:

HttpResponseMessage resp = client.GetAsync(
  String.Format("api/Appointments?dates.StartDate={0}&dates.EndDate={1}", 
    dates.StartDate.ToString(),
    dates.EndDate.ToString())).Result;

答案 1 :(得分:3)

如果您尝试通过查询字符串传递复杂对象,则需要使用[FromUri]属性修饰Get方法参数:

public IEnumerable<Appointment> GetAppointments([FromUri] SchedulerDateSpan dates)

您的查询字符串将如下所示:

http://server.com/api/Appointments?StartDate=blah1&EndDate=blah2
祝你好运!