MVC的WebAPI获取传递对象在C# [英] MVC WebApi Get passing an object in C#

查看:1542
本文介绍了MVC的WebAPI获取传递对象在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从,到目前为止我的MVC的WebAPI得到一个检索那些日期之间的项目。这是我最喜欢的事情我已经试过了没有工作(我已经试过几件事情)。

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; }
}

下面是我的控制器类的get:

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;
}

下面是从客户那里日期的类型是SchedulerDateSpan的我的电话:

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;
          ......
}

我也试着将其更改为这似乎工作,认沽但我无法解析与 Content.ReadAsAsync

任何建议都AP preciated

Any suggestions are appreciated

推荐答案

默认情况下,复杂类型(如您SchedulerDateSpan)预计将在请求体传递。你必须改变,如果你想从URI传递的值标记操作参数为[FromUri]:

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;

这篇关于MVC的WebAPI获取传递对象在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆