简体   繁体   中英

Most elegant way of checking the value of a query string parameter if not null?

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

The above seems cludgey. Is there a more elegant/compact way of checking if a query string parameter is not null and if so - retrieving the value of it?

I thought first of offering

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

but quickly realized that with strings, comparing some string with null is fine, and will produce false, so really just using this will work:

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

You can use String.IsNullOrEmpty

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

Or

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

}

I personally would go with a simple set of extension methods, something like this:

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

and a sample usage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM