C# WebApi Get请求方式传递实体参数的方法示例
作者:左直拳 时间:2023-05-01 21:46:46
前言
我又搞回笃NET啦!java之路真是命运多舛,好事多磨。不过,也许我已经进入无招胜有招,博取众家之长、融会贯通的地步了。
对于WebApi,今天又有了一些新的了解。
话说,Get请求方式,参数会附在Url后面,称为QueryString,传递给服务器;而POST方式,则将参数放在消息体内。采用QueryString的话,简单,方便,但只适合参数比较少的情况;但有的时候,需要传递比较多、比较复杂的参数,比如,组合条件查询。
组合条件查询,条件会很多,通常会用一个实体类来封装,传递给服务器。用post方式肯定是可以的,驾轻就熟。问题是,RESTful原则,是将一切抽象成资源,对资源的不同请求方式,代表了对资源的不同操作。按道理,post难道不是代表插入吗?为啥查询也要用到post?
GET方式下,也可以将参数提交给服务器?但查来查去,ajax好像可以;但服务器端,使用WebClient就没有找到现成的例子,不知道该咋整。只好用最原始的方法,将实体类转化成QueryString,附在地址后面了。有两个问题:
1、实体类如何转换成QueryString这种键值对格式?
2、服务器端如何提取?
一、实体类如何转换成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();
}
来源:https://blog.csdn.net/leftfist/article/details/89190459
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Springboot使用@RefreshScope注解实现配置文件的动态加载
![](https://img.aspxhome.com/file/2023/9/69909_0s.jpg)
c# BackgroundWorker组件的作用
![](https://img.aspxhome.com/file/2023/5/111105_0s.jpg)
Java 实战项目之小说在线阅读系统的实现流程
![](https://img.aspxhome.com/file/2023/4/86824_0s.png)
C#调用C++DLL传递结构体数组的终极解决方案
C语言安全编码之数组索引位的合法范围
Android实现图片循环播放的实例方法
C#设置与获取环境变量的方法详解
Spring Boot集成Ehcache缓存解决方式
c++野指针的原理以及避免方法
简单谈谈Java 中的线程的几种状态
使用SpringBoot+OkHttp+fastjson实现Github的OAuth第三方登录
![](https://img.aspxhome.com/file/2023/9/126339_0s.png)
java 串口通信实现流程示例
C++实现LeetCode(9.验证回文数字)
WPF+SkiaSharp实现自绘弹幕效果
![](https://img.aspxhome.com/file/2023/6/98186_0s.gif)
Java获取当前时间年月日的方法
App内切换语言详解
![](https://img.aspxhome.com/file/2023/5/137435_0s.gif)
C#实现系统托盘通知的方法
Java中常用的设计模式之观察者模式详解
![](https://img.aspxhome.com/file/2023/0/75450_0s.png)
详解IntelliJ IDEA中TortoiseSVN修改服务器地址的方法
![](https://img.aspxhome.com/file/2023/0/59490_0s.png)
Android开发使用Databinding实现关注功能mvvp
![](https://img.aspxhome.com/file/2023/2/102592_0s.jpg)