Ani*_*mar 2 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; }
}
Run Code Online (Sandbox Code Playgroud)
现在,如何传递passenger和contactinfo 参数,上述服务.
webapiconfig文件有什么变化吗?我想通过这样的乘客详情:
passengername="pavan",
age="23",
Gender="M",
passengername="kumar",
Gender="M",
Age="22
Run Code Online (Sandbox Code Playgroud)
如果您可以创建参数模型,那将更加简洁.要从客户端传递它们,您需要使用数据交换格式之一格式化它们.我更喜欢使用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; }
}
Run Code Online (Sandbox Code Playgroud)
客户端
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);
}
}
Run Code Online (Sandbox Code Playgroud)