MVC-路由(Route)

1.启用路由前的准备工作

Global.asax.cs中注册路由

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //===============注册区域===============
            AreaRegistration.RegisterAllAreas();
            //===========注册路由======================还可以注册全局过滤器...
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

2.App_Start\RouteConfig.cs配置路由

1.传统路由的配置与使用

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Login_", action = "Index", id = UrlParameter.Optional }
//标准项目的标准配置,http://localhost:8080/的默认首页是http://localhost:8080/Login_/index
            );
        }

2.属性路由路由的配置与使用

public static void RegisterRoutes(RouteCollection routes)
        {
            //启用属性路由//要放在上面!!!!!!!!!!!!有顺序要求的!!!
            routes.MapMvcAttributeRoutes();

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Login_", action = "Index", id = UrlParameter.Optional }
            );
        }

使用(在Controller中用):

using System.Web.Mvc;
namespace JJQ_Practice.Controllers
{
    public class addController : Controller
    {
        [Route("specialRoutTest")]
        // GET: add
        public ActionResult Index()
        {
            return Content("hello-jjq");
        }
    }
}

使用(在url或其他url应用中用):

访问
http://localhost:8080/specialRoutTest
即可进入addController 对应的控制器

你可能感兴趣的:(MVC-路由(Route))