I build a site in mvc3 , i want to restrict my site on firefox .
i mean to say that when anyone open my site on firefox it open correctly but when anyone opens it on chrome or IE it give an customze error . I am using c# with mvc3
You could write a global action filter which will test the User-Agent HTTP request header:
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();
}
}
and then register this filter in Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new FireFoxOnlyAttribute());
}
You are looking for the user-agent of the user connected to your website, which may be retrieved via this call in your controller:
Request.UserAgent
Not that I agree with such a pattern, though.
This is a simple javascript function you may add to your code and perform the actions against.
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.
}
}
On main page you may call the function on page load event. Though this practice is not recommended.
You could test the Request.UserAgent as part of a constraint on the route.
For example, you could define a route constraint routine as follows:
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);
}
}
Then add the following constraint to a route:
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
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.