Server-side detection if the browser is an Internet Explorer browser in the ASP.NET core

I am trying to determine if the Internet Explorer browser in ASP.NET Core is server side.

In a previous version of ASP.NET 4 in my cshtml:

@if (Request.Browser.Browser == "IE") { //show some content } 

but in ASP.NET 5 / ASP.NET Core intellisense for Context.Request does not have an option for Browser

I can get a UserAgent, but this seems rather complicated as IE has several line types

 Context.Request.Headers["User-Agent"] 

for Internet Explorer 11.0 I get

  Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko 

making it difficult to identify any past, current, or future versions of IE.

+7
asp.net-core asp.net-core-mvc
source share
2 answers

I feel obligated to say that, as a rule, it is best to try to avoid sniffing the browser on the server side if you can. But I fully understand that sometimes it can be useful. So that...

Based on this list, http://www.useragentstring.com/pages/useragentstring.php?name=Internet+Explorer looks like UserAgent for almost all versions of Internet Explorer contains MSIE, so this will be the main task you would like to search for.

Interestingly, while looking at this list of IE user agents, the user agent you are observing is one of the few that does not contain MSIE. If you check for an MSIE or Trident in a user agent that should work well to identify all cases of Internet Explorer.

(Trident is a linking mechanism that uses Internet Explorer and is used only for Internet Explorer)

So, for example, code to determine if the browser is IE can be written as:

  public static bool IsInternetExplorer(string userAgent) { if(userAgent.Contains("MSIE") || userAgent.Contains("Trident")) { return true; } else { return false; } } 

And this can be called from the controller in this way:

 string userAgent = Request.Headers["User-Agent"]; if(IsInternetExplorer(userAgent)) { //Do your special IE stuff here } else { //Do your non IE stuff here } 
+9
source share

I applied the extension method to evaluate this:

 public static bool IsInternetExplorer(string userAgent) { return (userAgent.Contains("MSIE") || userAgent.Contains("Trident")); } // Extension for Request public static bool IsInternetExplorer(this HttpRequestBase req) { return IsInternetExplorer(req.Headers["User-Agent"]); } 

Using:

 if (Request.IsInternetExplorer()) { // Do something microsofty } 

(Based on Ron C's answer)

0
source share

All Articles