1

I have tried to check the browser in RouteConfig.cs file, but its showing error that didn't get the request from browser.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    string browser = HttpContext.Current.Request.Browser.Browser;
    if (browser == "Chrome" || browser == "Firefox")
    {
        routes.MapRoute(name: "Default",
                        url: "{controller}/{action}/{id}",
                        defaults: new
                                  {
                                      controller = "Login",
                                      action = "Index",
                                      id = UrlParameter.Optional
                                  });
    }              
}

My goal is to access applications only from chrome and firefox, so I have tried to check it in RouteConfig to re-route to another view if condition not satisfied. But it's not working so I have checked with Global.asax but the routing is not working there.

Dhanil Dinesan
  • 575
  • 9
  • 27
  • 1
    What is the goal that you want to achieve here? ( Functionally ) – Kristóf Tóth Jul 23 '19 at 12:34
  • @KristófTóth i have edited my question please check – Dhanil Dinesan Jul 23 '19 at 12:40
  • Yes just as @Patrick said it is not the concern of the startup of your application to handle a specific request. You have to do this in the controller(s) e.g. if a request contains indication that it isn't from ffox or chrome return http 404 or 500 or whatever you can work with `currentRequest.Headers.UserAgent` in your controller for example. https://stackoverflow.com/questions/17306038/how-would-you-detect-the-current-browser-in-an-api-controller – Kristóf Tóth Jul 23 '19 at 12:42

2 Answers2

1

You can't check for the browser at startup, since the startup isn't related to a request, so no browser to check there.

The best option you have is to check in the action or controller itself what the browser is. I would be wary though to exclude specific browsers form visiting your site, as it looks like you are trying now.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

For browser-checking, a good option is to configure a middleware class that you can use to check each http request, and potentially specify a redirect or response. It is a suitable way to contain this logic all in one place, so you don't need to duplicate across controllers or actions, and is really easy to set up. Lots of articles are available online.

Michael
  • 473
  • 5
  • 12