c# – 多个可选查询字符串参数REST API GET

c# – 多个可选查询字符串参数REST API GET,第1张

概述我正在使用web api 2来实现一个宁静的服务.在对最佳实践进行一些研究之后,每个人似乎都对如何做以下事情有不同的看法.我有一个GET public HttpResponseMessage Get(string crewId, string shiftDate, int offset = 1, int limit = 10) 此GET方法返回一个列表.有多种方法可以从此方法获取数据. >只有船员 我正在使用web API 2来实现一个宁静的服务.在对最佳实践进行一些研究之后,每个人似乎都对如何做以下事情有不同的看法.我有一个GET
public httpResponseMessage Get(string crewID,string shiftDate,int offset = 1,int limit = 10)

此GET方法返回一个列表.有多种方法可以从此方法获取数据.

>只有船员才能获得
>仅通过shiftDate获取
要么
>通过crewID和shiftDate获取

你(1)将crewID和shiftDate标记为可选吗?

public httpResponseMessage Get(string crewID = null,string shiftDate = null,int limit = 10)

然后有一堆if语句来检查填充的内容和未填充的内容以便能够执行 *** 作

if(crewID != null && shiftDate == null){  // Get by crewID}else if(crewID == null && shiftDate != null){  // Get By shiftDate}else if(crewID != null && shiftDate != null){  // Get By crewID and shiftDate}

对我来说这看起来很疯狂,特别是如果你有很多参数,你的代码中会有太多“if”语句.

你(2)有不同的获取?

public httpResponseMessage GetByCrewID(string crewID,int limit = 10)public httpResponseMessage GetByShiftDate(string shiftDate,int limit = 10)public httpResponseMessage GetByCrewIDShiftDate(string crewID,int limit = 10)

然后你将URI路由映射到方法

> … / API / GetByCrewID?crewID = 1234
> … / API / GetByShiftDate?shiftDate = 1111-11-11
> … / API / GetByCrewIDShiftDate?crewID = 1234& shiftDate = 1111-11-11

选项2是否宁静?

或者有更好的选择(3).

上述两个选项都可以确保我使用最佳实践并遵循REST标准.看起来我错过了什么,希望你能把我放在正确的方向.

解决方法 您不希望选项(2) – 在您的URL中想要名词是RESTful.

所以你希望你的网址看起来像:

/API/items/?crewID=1234&shiftDate=1111-11-11

(根据’Crew’和’Shift’参数名称,我无法弄清楚你的物品是什么.什么有船员和轮班日期?钓鱼之旅?如果是这样,网址会更好/ / API ?/钓鱼人次/ crewID = ….&放大器; shiftDate = …

至于控制器,我会去做类似的事情:

public httpResponseMessage Get(string crewID = null,int limit = 10) {    return dataSource.Where(x=> (x.CrewID == crewID || crewID == null)            && (x.ShiftDate == shiftDate || shiftDate == null));}
总结

以上是内存溢出为你收集整理的c# – 多个可选查询字符串参数REST API GET全部内容,希望文章能够帮你解决c# – 多个可选查询字符串参数REST API GET所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1262746.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-08
下一篇2022-06-08

发表评论

登录后才能评论

评论列表(0条)

    保存