我试图阻止用户访问 abc.com/Home/Index
,而是希望用户只能通过 abc.com
访问主页。我使用以下代码但不起作用。
// 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"}
);
最佳答案
您只需忽略 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 }
);
}
}
然后服务器将返回 404 not find 而不是页面。
当然,如果您想删除整个应用程序的所有备用路径,则需要删除 Default
路由的默认值,这将使它们成为必需的。
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 }
);
}
}
现在您也无法通过 /Home/
访问主页(这是使用默认路由访问它的另一个路由)。
当然,最好的选择是使用 canonical tag确保不会有其他可能溜走的路线损害您的 SEO 分数。
<link rel="canonical" href="http://example.com/" />
关于asp.net-mvc - 从 mvc 5 主页默认路由中删除主页索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32474711/