Teresa Burger
Teresa Burger

Reputation: 147

MVC WebApi Get passing an object in C#

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

Upvotes: 4

Views: 12814

Answers (2)

tcarvin
tcarvin

Reputation: 10855

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!

Upvotes: 4

Maggie Ying
Maggie Ying

Reputation: 10175

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;

Upvotes: 7

Related Questions