如何将参数传递给webapi中的数组类?

时间:2015-10-25 06:40:58

标签: c# asp.net-mvc asp.net-web-api2

我是asp.net mvc webapi的新手。我正在创建一个webapi服务。在这个服务中,我将参数作为数组类发送。

以下是我的服务:

[AcceptVerbs("GET", "POST")]
public HttpResponseMessage addBusOrder(string UserUniqueID, int PlatFormID,
                                       string DeviceID, int RouteScheduleId,
                                       string JourneyDate, int FromCityid,
                                       int ToCityid, int TyPickUpID,
                                       Contactinfo Contactinfo, passenger[] pass)
{
    //done some work here
}

public class Contactinfo
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phoneno { get; set; }
    public string mobile { get; set; }
}

public class passenger
{
    public string passengerName { get; set; }
    public string Age { get; set; }
    public string Fare { get; set; }
    public string Gender { get; set; }
    public string Seatno { get; set; }
    //public string Seattype { get; set; }
    // public bool Isacseat { get; set; }
}

现在如何将passengercontactinfo参数传递给上述服务。

webapiconfig文件有变化吗?  我想通过这样的乘客详情:

passengername="pavan",
age="23",
Gender="M",

passengername="kumar",
Gender="M",
Age="22

2 个答案:

答案 0 :(得分:5)

如果您可以创建参数模型,那将更加简洁。要从客户端传递它们,您需要使用数据交换格式之一格式化它们。我更喜欢使用Newtonsoft.Json库提供的JSON。发送过程由System.Net.Http命名空间提供的HttpClient类处理。以下是一些示例:

服务器端

    //Only request with Post Verb that can contain body
    [AcceptVerbs("POST")]
    public HttpResponseMessage addBusOrder([FromBody]BusOrderModel)
    {
        //done some work here
    }

    //You may want to separate model into a class library so that server and client app can share the same model
        public class BusOrderModel
        {
            public string UserUniqueID { get; set; }
            public int PlatFormID { get; set; }
            public string DeviceID { get; set; }
            public int RouteScheduleId { get; set; }
            public string JourneyDate { get; set; }
            public int FromCityid { get; set; }
            public int ToCityid { get; set; }
            public int TyPickUpID { get; set; }
            public Contactinfo ContactInfo { get; set; }
            public passenger[] pass { get; set; }
        }

客户端

    var busOrderModel = new BusOrderModel();
    var content = new StringContent(JsonConvert.SerializeObject(busOrderModel), Encoding.UTF8, "application/json");

    using (var handler = new HttpClientHandler())
    {
            using (HttpClient client = new HttpClient(handler, true))
            {
              client.BaseAddress = new Uri("yourdomain");
              client.DefaultRequestHeaders.Accept.Add(
                  new MediaTypeWithQualityHeaderValue("application/json"));

              return await client.PostAsync(new Uri("yourdomain/controller/addBusOrder"), content);
            }
    }

答案 1 :(得分:1)

以下是您可以这样做的方法:

首先,由于您将两个对象作为参数传递,我们需要一个新类来保存它们(因为我们只能将一个参数绑定到请求的内容):

public class PassengersContact
{
    public Passenger[] Passengers { get; set; }
    public Contactinfo Contactinfo { get; set; }
}

现在为您的控制器(这只是一个测试控制器):

[RoutePrefix("api")]
public class DefaultController : ApiController
{

    [HttpPost]
    // I prefer using attribute routing
    [Route("addBusOrder")]
    // FromUri means that the parameter comes from the uri of the request
    // FromBody means that the parameter comes from body of the request
    public IHttpActionResult addBusOrder([FromUri]string userUniqueId,
                                            [FromUri]int platFormId,
                                            [FromUri]string deviceId, [FromUri]int routeScheduleId,
                                            [FromUri]string journeyDate, [FromUri]int fromCityid,
                                            [FromUri]int toCityid, [FromUri]int tyPickUpId,
                                            [FromBody]PassengersContact passengersContact)
    {
        // Just for testing: I'm returning what was passed as a parameter
        return Ok(new
        {
            UserUniqueID = userUniqueId,
            PlatFormID = platFormId,
            RouteScheduleId = routeScheduleId,
            JourneyDate = journeyDate,
            FromCityid = fromCityid,
            ToCityid = toCityid,
            TyPickUpID = tyPickUpId,
            PassengersContact = passengersContact
        });
    }
}

您的请求应如下所示:

POST http://<your server's URL>/api/addBusOrder?userUniqueId=a&platFormId=10&deviceId=b&routeScheduleId=11&journeyDate=c&fromCityid=12&toCityid=13&tyPickUpId=14
Content-Type: application/json
Content-Length: 110

{
    "passengers" : [{
            "passengerName" : "name",
            "age" : 52
            /* other fields go here */
        }
    ],
    "contactinfo" : {
        "name" : "contact info name",
        /* other fields go here */
    }
}

请注意,api/addBusOrder来自连接RoutePrefix/Route属性的值。