I need to get a from and to date to my mvc webapi for retrieving items between those dates. Here is my favorite thing I have tried that has not worked (I have tried several things).
I have an object that is shared between the projects:
public class SchedulerDateSpan
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
Here is my controller class for 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;
}
Here is my call from the client where dates is of type 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;
......
}
I also tried changing it to a put which seemed to work but then I couldn't parse the results with Content.ReadAsAsync
Any suggestions are appreciated
By default, complex type (such as your SchedulerDateSpan) are expected to be passed in the request body. You'll have to change mark the action parameter to be [FromUri] if you want the value to be passed from the URI:
public IEnumerable<Appointment> GetAppointments([FromUri]SchedulerDateSpan dates)
{...}
You can then pass the 'dates' from the query string in the Uri, like this:
HttpResponseMessage resp = client.GetAsync(
String.Format("api/Appointments?dates.StartDate={0}&dates.EndDate={1}",
dates.StartDate.ToString(),
dates.EndDate.ToString())).Result;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With