处理查询字符串的最佳方法[关闭]

问题描述 投票:0回答:1

我正在努力理解使用单个方法和可选参数来接受Get方法与ApiController的查询参数之间的区别。

我在浏览器中编写了代码,原谅任何错误。为简洁起见,我也遗漏了其他基本行动。

以下是我给定网址的选项(我计划有更多可以选择传入的查询字符串):

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;
}

有什么不同?

c# .net rest asp.net-web-api2
1个回答
2
投票

虽然您的第一个示例可以被视为更精确,更适合(如果您在每个函数中确实有不同的功能),有些人会认为它很冗长。

话虽如此,当您使用可选参数时,在稍后阶段会出现一些可怕的问题(在示例2中)。 (虽然我有点像例子2)

请参阅here,它解释了优点和缺点......但最重要的是参数在编译时填充,而不是运行时...所以任何接口都会更改,或者可选参数值的更改可能无法获取通过调用您的函数的其他库。因此,如果您决定将默认值更改为新值,它们实际上可能会传递较旧的默认值。

© www.soinside.com 2019 - 2024. All rights reserved.