asp.net-mvc - 从 mvc 5 主页默认路由中删除主页索引

标签 asp.net-mvc asp.net-mvc-4 asp.net-mvc-5 routes asp.net-mvc-routing

我试图阻止用户访问 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/

相关文章:

asp.net-mvc - 带有 MVC4 模型绑定(bind)的 Angular JS 因日期/日期时间而失败?

c# - API 路由抛出 "Resource Not Found"错误

asp.net-mvc - MVC5 : Can @Html. TextBoxFor(或EditorFor)从模型的数据注释中获取其MaxLength?

c# - 用于包装 JsonResult 操作响应的 .Net 过滤器

c# - ASP.NET Core MVC,从数据库中获取文件,并呈现为图像

C# Linq To Excel 获取不在第一行开始的表数据

c# - 错误: System. Data.SqlClient.SqlException:不允许新事务,因为 session 中有其他线程在运行

c# - GoogleOAuth2AuthenticationOptions 将 access_type 设置为离线

c# - 使用 Razor 的 ASP.net MVC 5 ViewBag

asp.net-mvc - 图像网址中的“&”号MVC导致潜在危险的Request.Path