I'm trying to determine if the browser is Internet Explorer in ASP.NET Core on the server side.
In previous ASP.NET 4 version in my cshtml:
@if (Request.Browser.Browser == "IE")
{
//show some content
}
but in ASP.NET 5/ASP.NET Core intellisense for Context.Request
doesn't have an option for Browser
I can get the UserAgent but this seems rather complex as IE has some many types of strings
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
which makes it very difficult to determine any past, current or future IE versions from it.
I feel obligated to say that it's typically best to try to avoid server side browser sniffing if you can. But I fully realize that sometimes it can be helpful. So...
Based on this list http://www.useragentstring.com/pages/useragentstring.php?name=Internet+Explorer it looks like UserAgent for almost all versions of Internet Explorer contain MSIE so that would be the primary thing you would want to look for.
Interestingly when looking over this list of IE user agents, the user agent you observed is one of the very few that does not contain MSIE. If you check for the presence of MSIE or Trident in the user agent that should work pretty well for identifying all cases of Internet Explorer.
(Trident is the layout engine that powers Internet Explorer and it's only used for Internet Explorer)
So for example the code to determine if the browser is IE could be written as:
public static bool IsInternetExplorer(string userAgent) {
if(userAgent.Contains("MSIE") || userAgent.Contains("Trident")) {
return true;
} else {
return false;
}
}
And this could be called from within the controller like this:
string userAgent = Request.Headers["User-Agent"];
if(IsInternetExplorer(userAgent)) {
//Do your special IE stuff here
} else {
//Do your non IE stuff here
}
In ASP.NET Core Pages and ASP.NET Core Blazor, you can use the following:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// ...
}
SomeComponent.razor
@inject IHttpContextAccessor HttpContextAccessor
@if (HttpContextAccessor.HttpContext != null
&& HttpContextAccessor.HttpContext.Request.IsInternetExplorer())
{
<input type="text" @bind="ViewModel.TextInput" />
}
else
{
<input type="date" @bind="ViewModel.DateTimeInput" />
}
HttpRequestExtensions.cs
public static class HttpRequestExtensions
{
public static bool IsInternetExplorer(this HttpRequest request)
{
return IsInternetExplorer(request.Headers["User-Agent"]);
}
private static bool IsInternetExplorer(string userAgent)
{
return userAgent.Contains("MSIE")
|| userAgent.Contains("Trident");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With