4

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

2 Answers 2

7

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a champ! Thank you!!
4

If you are trying to pass a complex object via the query string then you need to decorate your Get method parameter with the [FromUri] attribute:

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

Your query string would look something like this:

http://server.com/api/Appointments?StartDate=blah1&EndDate=blah2

Good luck!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.