Reading userAgent using C #

I have the following code that reads userAgent and does some logic based on values ​​mapped using indexOf:

String userAgent; userAgent = Request.UserAgent; // If it not IE if (userAgent.IndexOf("MSIE") < 0) { return RedirectToAction("Index", "Home", new { area = "Dashboard" }); } // If it IE BUT ChromeFrame else if(userAgent.IndexOf("ChromeFrame") > -1) { return RedirectToAction("Index", "Home", new { area = "Dashboard" }); } // It just IE else { return View("ChromeFrame"); } 

If it is IE, then it should return the view or its IE, but it contains a ChromeFrame, then it should redirect, and then the other browser should redirect.

I think the problem is with the code part > 0 . What is the correct way to compare information? Thanks.

+6
source share
3 answers

Just use the containing method , which will make your code less cryptic and less error prone.

 if (userAgent.Contains("MSIE")) { return RedirectToAction("Index", "Home", new { area = "Dashboard" }); } 
+7
source

You should use > -1 , because otherwise it will not work if the substring is at the beginning of the line.

+1
source

IndexOf returns -1 if the row is not found ... see MSDN for reference.

+1
source

Source: https://habr.com/ru/post/907009/


All Articles