这篇文章将为大家详细讲解有关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请求方式传递实体参数的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
当前文章:C#中WebApiGet请求方式传递实体参数的示例分析
链接地址:https://www.cdcxhl.com/article34/gigspe.html
成都网站建设公司_创新互联,为您提供响应式网站、静态网站、移动网站建设、网站设计公司、手机网站建设、标签优化
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联