Reputation: 587
I am trying to prevent user to access abc.com/Home/Index
, instead i want user to be able to access home page via abc.com
only. I use the following code but not work.
// This code restict user to access abc.com/home/index
// Only allow user to access abc.com/home
routes.MapRoute(
"OnlyAction",
"{action}",
new { controller = "Home", action = "Index" }
);
// This code does not work, I am expecting this code to allow
// user to access home only at abc.com
routes.MapRoute(
"Home",
"",
new { controller = "Home", action = "Index"}
);
Upvotes: 2
Views: 2893
Reputation: 56859
You just need to ignore the URL:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Ignore the alternate path to the home page
routes.IgnoreRoute("Home/Index");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Then the server will return a 404 not found instead of a page.
Of course, if you wanted to remove all of the alternate paths for the entire application, you would need to remove the default values of the Default
route, which will make them required.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Ignore the alternate path to the home page
routes.IgnoreRoute("Home/Index");
routes.MapRoute(
name: "Home",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
Now you won't be able to access the home page by /Home/
, either (which is another route that accesses it using the default route).
Of course, the best option is to use the canonical tag to ensure no additional routes that may slip through damage your SEO score.
<link rel="canonical" href="http://example.com/" />
Upvotes: 4