繁体   English   中英

如何限制浏览器

[英]How to Restrict Browser

我在mvc3中建立了一个网站,我想在firefox上限制我的网站。

我的意思是说,当有人在firefox上打开我的网站时,它可以正确打开,但是当有人在chrome或IE上打开它时,则会出现定制错误。 我在mvc3中使用c#

您可以编写一个全局操作过滤器 ,该过滤器将测试User-Agent HTTP请求标头:

public class FireFoxOnlyAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var userAgent = filterContext.HttpContext.Request.Headers["User-Agent"];
        if (!IsFirefox(userAgent))
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "~/Views/Shared/Unauthorized.cshtml"
            };
        }
    }

    private bool IsFirefox(string userAgent)
    {
        // up to you to implement this method. You could use
        // regular expressions or simple IndexOf method or whatever you like
        throw new NotImplementedException();
    }
}

然后在Global.asax中注册此过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new FireFoxOnlyAttribute());
}

您正在寻找连接到您网站的用户的用户代理,可以通过控制器中的此调用来检索该用户代理:

Request.UserAgent

不过,我并不同意这种模式。

这是一个简单的javascript函数,您可以将其添加到代码中并对其执行操作。

function detect_browser() {
    var agt=navigator.userAgent.toLowerCase();
    if (agt.indexOf("firefox") != -1) return true;
    else{
        window.location="";//Here within quotes write the location of your error page.
    }
}

在主页上,您可以调用页面加载事件函数。 虽然不建议这种做法。

您可以将Request.UserAgent测试为路由约束的一部分。

例如,您可以如下定义路线约束例程:

public class UserAgentConstraint : IRouteConstraint
{
    private string requiredUserAgent;

    public UserAgentConstraint(string agentParam)
    {
        requiredUserAgent = agentParam;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(requiredUserAgent);
    }
}

然后将以下约束添加到路由:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, //Parameter defaults
    new { customConstraint = new UserAgentConstraint("Firefox") } //Constraint
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM