2012-06-29 80 views
9
if(Page.Request.QueryString["ParamName"] != null) 
    if(Page.Request.QueryString["ParamName"] == expectedResult) 
    //Do something spectacular 

上面看起来很乱。有没有更优雅/紧凑的方式来检查查询字符串参数是否为空,如果是 - 检索它的值?检查查询字符串参数值的最优雅方式是否为空?

+0

http://stackoverflow.com/questions/ 349742/how-do-you-test-your-request-querystring-variables –

回答

10

我想先提供

if ((Page.Request.QueryString["ParamName"] ?? "") == expectedResult) { 

,但很快意识到,用绳子,用空比较一些字符串是好的,并会产生虚假的,所以真的只是使用这将工作:

if(Page.Request.QueryString["ParamName"] == expectedResult) 
    //Do something spectacular 
7

您可以使用String.IsNullOrEmpty

String.IsNullOrEmpty(Page.Request.QueryString["ParamName"]); 

或者

var parm = Page.Request.QueryString["ParamName"] ?? ""; 
if(parm == expectedResult) 
{ 

} 
+0

ParamName的值是什么?你只解决了我的代码的第一行(实际上,我应该真的使用IsNullOrEmpty - 所以+1)。 –

1

我个人用一组简单的扩展方法,像这样走:

public static class RequestExtensions 
{ 
    public static string QueryStringValue(this HttpRequest request, string parameter) 
    { 
     return !string.IsNullOrEmpty(request.QueryString[parameter]) ? request.QueryString[parameter] : string.Empty; 
    } 

    public static bool QueryStringValueMatchesExpected(this HttpRequest request, string parameter, string expected) 
    { 
     return !string.IsNullOrEmpty(request.QueryString[parameter]) && request.QueryString[parameter].Equals(expected, StringComparison.OrdinalIgnoreCase); 
    } 
} 

和样例用法

string value = Page.Request.QueryStringValue("SomeParam"); 
bool match = Page.Request.QueryStringValueMatchesExpected("SomeParam", "somevaue"); 
+0

最好是编写完整,快速和容易理解的代码,以便其他开发人员首先查看可能会继续执行代码的内容。另外,如果你看到你写的代码是多少代码产品,你会意识到你编写的代码很慢。一个简单的'=='完成了这项工作。 – Aristos

+0

很高兴接受批评,但你能解释代码是如何被认为是“缓慢”? – Kane

+0

因为我也接受批评,所以我收回慢代码,检查它并编译创建我所看到的内容,而不是一开始就想到的额外转换。 (我的意思是有很多额外的检查,只需要'==',但它是我们所看到的) – Aristos

相关问题