如果浏览器是ASP.NET Core中的Internet Explorer,则检测服务器端

gre*_*eay 8 asp.net-core-mvc asp.net-core

我正在尝试确定浏览器是否是服务器端ASP.NET Core中的Internet Explorer.

在我之前的cshtml中的ASP.NET 4版本中:

@if (Request.Browser.Browser == "IE")
{
    //show some content
}
Run Code Online (Sandbox Code Playgroud)

但在ASP.NET 5/ASP.NET Core intellisense Context.Request中没有选项Browser

我可以获得UserAgent,但这似乎相当复杂,因为IE有许多类型的字符串

Context.Request.Headers["User-Agent"]
Run Code Online (Sandbox Code Playgroud)

对于Internet Explorer 11.0,我得到了

 Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Run Code Online (Sandbox Code Playgroud)

这使得很难从中确定任何过去,现在或将来的IE版本.

Ron*_*n C 14

我觉得有必要说,如果可以的话,通常最好尽量避免服务器端浏览器嗅探.但我完全意识到有时它可能会有所帮助.所以...

根据此列表http://www.useragentstring.com/pages/useragentstring.php?name=Internet+Explorer,几乎所有版本的Internet Explorer都显示UserAgent包含MSIE,因此这将是您希望看到的主要内容对于.

有趣的是,在查看此IE用户代理列表时,您观察到的用户代理是少数不包含MSIE的用户代理之一.如果您检查用户代理中是否存在MSIE或Trident,它们可以很好地识别Internet Explorer的所有情况.

(Trident是为Internet Explorer提供支持的布局引擎,它仅用于Internet Explorer)

因此,例如,确定浏览器是否为IE的代码可以写为:

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

这可以在控制器内调用,如下所示:

string userAgent = Request.Headers["User-Agent"];

if(IsInternetExplorer(userAgent)) {
    //Do your special IE stuff here

} else {
    //Do your non IE stuff here
}
Run Code Online (Sandbox Code Playgroud)


Mov*_*GP0 7

在 ASP.NET Core Pages 和 ASP.NET Core Blazor 中,您可以使用以下内容:

启动文件

public void ConfigureServices(IServiceCollection services)
{
     services.AddHttpContextAccessor();
     // ...
}
Run Code Online (Sandbox Code Playgroud)

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" />
}
Run Code Online (Sandbox Code Playgroud)

HttpRequestExtensions.cs

@inject IHttpContextAccessor HttpContextAccessor

@if (HttpContextAccessor.HttpContext != null 
  && HttpContextAccessor.HttpContext.Request.IsInternetExplorer())
{
    <input type="text" @bind="ViewModel.TextInput" />
}
else
{
    <input type="date" @bind="ViewModel.DateTimeInput" />
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

6164 次

最近记录:

5 年,11 月 前