zoukankan      html  css  js  c++  java
  • 【转】Asp.net MVC定义短网址

    在MVC的逻辑代码里,Controller和Action是必须的,但是在网址里,并不需要完全体现Controller和Action。比如我们经常希望看到http://localhost/About而不是http://localhost/Home/About。

    默认的路由规则

    新建MVC应用程序后,Global.asax里默认注册的路由规则是:

    public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     
                routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
            }

    我们可以定义自己的路由规则。

    定义短网址

    我们定义一个可以用http://localhost/About等同于http://localhost/Home/About的路由规则:

    routes.MapRoute(
        "ShortAbout",
        "About",
        new { controller = "Home", action="About" }
    );

    此时访问http://localhost/About和http://localhost/Home/About是一样的。

    以上语句只定义了一个短网址,为了普遍性,可以这样定义路由规则:

    routes.MapRoute(
        "ActionOnly",
        "{action}/{id}",
        new { controller = "Home", action = "About", id = UrlParameter.Optional }
    );

    为了减少对其他Controller下默认Action(URL无Action)的影响,可对Action作限制:

    routes.MapRoute(
        "ActionOnly",
        "{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new { action = "About|Index" }
    );


  • 相关阅读:
    python socket文件传输实现
    python 进程与线程(理论部分)
    python函数-基础篇
    python变量、注释、程序交互、格式化输入、基本运算符
    python基础数据篇
    python基础之从认识python到python的使用
    判断素数
    辗转相除法
    你了解gets()和scanf()吗
    密码破译
  • 原文地址:https://www.cnblogs.com/hycms/p/5791472.html
Copyright © 2011-2022 走看看