这篇文章将为大家详细讲解有关C#中WebApi Get请求方式传递实体参数的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
一、实体类如何转换成QueryString这种键值对格式?
叫键值对可能不够专业,叫NameValueCollection?
很遗憾,也没找到啥现成的例子。
最后祭出反射,来拼装QueryString
二、服务器端如何提取QueryString里参数,自动变成一个实体类?
参数前面标注[FromUri]特性
上代码。
实体类:
namespace BaseLT.Core.Contract
{
public class Request
{
public Request();
public int Top { set; }
public int PageSize { get; set; }
public int PageIndex { get; set; }
public string OrderBy { get; set; }
public int SortState { get; set; }
public bool CompareObject<T>(T obj1, T obj2);
public void ExtjsInit();
}
}
WebApi服务器端:
public class TankController : ApiController
{
[HttpGet]
[Route("api/tank/matters/public/{id=0}")]
public IEnumerable<Matter> Get(int id,[FromUri]Request req)
{
return do sth;
}
}
客户端:
[TestMethod]
public void TestTankApi()
{
string url = "http://localhost/ybjzuser.api/api/tank/matters/public/";
url += getQueryString(new Request()
{
PageIndex = 1,
PageSize = 100
});
string re;
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.GetEncoding("utf-8");
re = webClient.DownloadString(url);
}
Assert.AreNotEqual(null, re);
Console.WriteLine(re);
}
static string getQueryString(Request req)
{
StringBuilder query = new StringBuilder("?");
PropertyInfo[] propertys = req.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (pi.CanRead)
{
query.Append($@"{pi.Name}={pi.GetValue(req)}&");
}
}
return query.ToString();
}
关于“C#中WebApi Get请求方式传递实体参数的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。