处理查询字符串的最佳方式
Best way to handle query string
我正在努力理解使用单独的方法和可选参数接受 Get
方法与 ApiController
.
的查询参数之间的区别
我在浏览器中编写了我的代码,所以请原谅任何错误。为了简洁起见,我还省略了其他基本操作。
这是我对给定 url 的选项(我计划有更多可以选择性传入的查询字符串):
GET http://myAppi.com/resources?color=red
GET http://myAppi.com/resources?color=red&shape=round
对于我的端点,我执行以下操作:
[Route("")]
public IEnumerable<string> Get(string color)
{
List<string> someList = new List<string>();
//some selecting linq color logic here
return someList;
}
[Route("")]
Public IEnumerable<string> Get(string color, string shape)
{
List<string> someList = new List<string>();
//some selecting linq color and shape logic here
return someList;
}
或者我是否使用可选参数...
[Route("")]
public IEnumerable<string> Get(string color, string shape = null)
{
List<string> someList = new List<string>();
if (String.IsNullOrWhiteSpace(shape))
{
//some selecting linq color logic here
}
else
{
//some selecting linq color and shape logic here
}
return someList;
}
有什么区别?
虽然您的第一个示例可以被视为更精确、更适合(如果您确实在每个函数中具有不同的功能),但有些人会认为它冗长。
话虽这么说,但是当您使用可选参数时(在示例 2 中),稍后可能会出现一些可怕的问题。 (虽然我有点喜欢示例 2)
参见 here,其中解释了优缺点...但最严重的缺点是参数是在编译时填充的,而不是 运行 时...因此任何接口都会发生变化,或者您的可选参数值的更改可能不会被调用您的函数的其他库获取。所以他们实际上可能会传递一个旧的默认值 - 如果您决定将默认值更改为新值。
我正在努力理解使用单独的方法和可选参数接受 Get
方法与 ApiController
.
我在浏览器中编写了我的代码,所以请原谅任何错误。为了简洁起见,我还省略了其他基本操作。
这是我对给定 url 的选项(我计划有更多可以选择性传入的查询字符串):
GET http://myAppi.com/resources?color=red
GET http://myAppi.com/resources?color=red&shape=round
对于我的端点,我执行以下操作:
[Route("")]
public IEnumerable<string> Get(string color)
{
List<string> someList = new List<string>();
//some selecting linq color logic here
return someList;
}
[Route("")]
Public IEnumerable<string> Get(string color, string shape)
{
List<string> someList = new List<string>();
//some selecting linq color and shape logic here
return someList;
}
或者我是否使用可选参数...
[Route("")]
public IEnumerable<string> Get(string color, string shape = null)
{
List<string> someList = new List<string>();
if (String.IsNullOrWhiteSpace(shape))
{
//some selecting linq color logic here
}
else
{
//some selecting linq color and shape logic here
}
return someList;
}
有什么区别?
虽然您的第一个示例可以被视为更精确、更适合(如果您确实在每个函数中具有不同的功能),但有些人会认为它冗长。
话虽这么说,但是当您使用可选参数时(在示例 2 中),稍后可能会出现一些可怕的问题。 (虽然我有点喜欢示例 2)
参见 here,其中解释了优缺点...但最严重的缺点是参数是在编译时填充的,而不是 运行 时...因此任何接口都会发生变化,或者您的可选参数值的更改可能不会被调用您的函数的其他库获取。所以他们实际上可能会传递一个旧的默认值 - 如果您决定将默认值更改为新值。