MVC WebApi在C#中传递一个对象

Ter*_*ger 3 asp.net-mvc json asp.net-web-api

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

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

public class SchedulerDateSpan
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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;
}
Run Code Online (Sandbox Code Playgroud)

这是来自客户端的调用,其中日期类型为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;
          ......
}
Run Code Online (Sandbox Code Playgroud)

我也尝试将它改为看似有效的看跌,但后来我无法解析结果 Content.ReadAsAsync

任何建议表示赞赏

Mag*_*ing 6

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

public IEnumerable<Appointment> GetAppointments([FromUri]SchedulerDateSpan dates)
{...}
Run Code Online (Sandbox Code Playgroud)

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

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