简体   繁体   中英

C# if statement with string.Contains() not working as expected

I am stuck on what I thought would be a really easy problem. I am trying to redirect a user to a different website if the UserAgent does not contain a series of strings. The part I can not figure out is that the if statement works fine if I use the code below. I am happy with the results with this but something tells me that it is not good practice to only have an else statement and perform nothing if the statement proves to be true.

        string strUserAgent = Request.UserAgent.ToString().ToLower();

        if (strUserAgent != null)
        {
            if (Request.Browser.IsMobileDevice == true || 
                strUserAgent.Contains("iphone") ||
                strUserAgent.Contains("blackberry") || 
                strUserAgent.Contains("mobile") ||
                strUserAgent.Contains("windows ce") || 
                strUserAgent.Contains("opera mini") ||
                strUserAgent.Contains("palm") ||
                strUserAgent.Contains("android"))
            {
                // Is this normal practice to only have an else block?
            }else
            {
                Response.Redirect(AppState["redirectBack"].ToString());
            }

When I try the next block of code the script redirects the user no matter what the UserAgent string contains. Can someone explain why this might be happening?

        string strUserAgent = Request.UserAgent.ToString().ToLower();

        if (strUserAgent != null)
        {
            if (Request.Browser.IsMobileDevice != true || 
                !strUserAgent.Contains("iphone") ||
                !strUserAgent.Contains("blackberry") || 
                !strUserAgent.Contains("mobile") ||
                !strUserAgent.Contains("windows ce") || 
                !strUserAgent.Contains("opera mini") ||
                !strUserAgent.Contains("palm") ||
                !strUserAgent.Contains("android"))
            {
                 Response.Redirect(AppState["redirectBack"].ToString());
            }

Invert your statement using ! ("not"):

if(!(conditions)) { }

This will avoid the need to use an empty code block and you can just drop the else .

Your second codeblock will redirect when you're not on a mobile device or when your useragent contains any of the following strings. It depends on your input and your environment.

Do note that it's a lot easier to create a collection of the possibilities and check if your useragent is in there:

if(new[] {"iphone", "somephone", "otherphone" }.Any(x => useragent.Contains(x))) {}

You need De Morgan's Law . When you inverted your condition, your ORs need to become ANDs

It will always be true that at least one of your conditions will not be true. For instance, if strUserAgent.Contains(iphone) will be false if strUserAgent.Contains("blackberry") is true.

You need to change your OR ( || ) operator to a logical AND ( && ) operator.

    if (strUserAgent != null)
    {
        if (Request.Browser.IsMobileDevice != true && 
            !strUserAgent.Contains("iphone") &&
            !strUserAgent.Contains("blackberry") && 
            !strUserAgent.Contains("mobile") &&
            !strUserAgent.Contains("windows ce") && 
            !strUserAgent.Contains("opera mini") &&
            !strUserAgent.Contains("palm") &&
            !strUserAgent.Contains("android"))
        {
             Response.Redirect(AppState["redirectBack"].ToString());
        }

Not an answer, just a suggestion. You can make your code cleaner with an extension method:

public static bool ContainsAnyOf(this string source, params string[] strings)
{
    return strings.Any(x => source.Contains(x));
}

And now write

if (strUserAgent.ContainsAnyOf("iphone", "blackberry", "mobile", "windows ce", "opera mini", "palm", "android"))
{
     //
}

You need to reverse the entire thing. Putting !A || !B !A || !B is not the same as !(A||B) . In the first one if its A then it's Not B so it's True . In the second one it's False .

   if (!(Request.Browser.IsMobileDevice == true || 
            strUserAgent.Contains("iphone") ||
            strUserAgent.Contains("blackberry") || 
            strUserAgent.Contains("mobile") ||
            strUserAgent.Contains("windows ce") || 
            strUserAgent.Contains("opera mini") ||
            strUserAgent.Contains("palm") ||
            strUserAgent.Contains("android")
      ) )
        {
            Response.Redirect(AppState["redirectBack"].ToString());
        }
 string strUserAgent = Request.UserAgent.ToString().ToLower();

    if (strUserAgent != null)
    {
        if (!(Request.Browser.IsMobileDevice == true || 
            strUserAgent.Contains("iphone") ||
            strUserAgent.Contains("blackberry") || 
            strUserAgent.Contains("mobile") ||
            strUserAgent.Contains("windows ce") || 
            strUserAgent.Contains("opera mini") ||
            strUserAgent.Contains("palm") ||
            strUserAgent.Contains("android")))            
        {
            Response.Redirect(AppState["redirectBack"].ToString());
        }

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