close
文章出處

概述


本文已經同步到《Asp.net Vnext 系列教程 》中]

ASP.NET 路由系統主要負責兩個操作:

傳入的 HTTP 請求映射路由處理程序給出路由集合

路由系統的責任找到匹配路由創建路由數據請求分配一個處理程序
選擇動作 MVC 的處理程序實現細節使用路由數據傳入請求其他信息選擇執行操作

代碼實現TemplateRoute 初始化路由 URL 模板


 

  public class MyTemplateRoute : TemplateRoute
        {
        public MyTemplateRoute(IRouteBuilder routeCollectionBuilder)
            : base(routeCollectionBuilder.DefaultHandler,
                   "{controller}/{action}/{id?}",
                  new RouteValueDictionary(new { controller = "Home", action = "Index" }),
                  new RouteValueDictionary(new { }),
                  new RouteValueDictionary(new { }),
                  routeCollectionBuilder.ServiceProvider.GetService<IInlineConstraintResolver>())
            {
            }

        public override Task RouteAsync(RouteContext context)
            {
            return base.RouteAsync(context);
            }
        }

啟動類

  public class Startup
    {
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
            {
            services.AddMvc();
            }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            
            {
                //加入模板 默認http://http://localhost/Home/Index
                routes.Routes.Add(new MyTemplateRoute(routes));
               

            });
            }
    }

實現IRouter添加默認路由

 public class DefaultRoute : IRouter
        {
      
        private readonly IRouter _next;

        public DefaultRoute(IRouter next)
            {
            _next = next;
            }

        public VirtualPathData GetVirtualPath(VirtualPathContext context)
            {
            return _next.GetVirtualPath(context);
            }

        public async Task RouteAsync(RouteContext context)
            {

            var oldRouteData = context.RouteData;
            var newRouteData = new RouteData(oldRouteData);
            newRouteData.Routers.Add(_next);
            newRouteData.Values["controller"] = "Home";
            newRouteData.Values["action"] = "Index";
            try
                {
                context.RouteData = newRouteData;
                await _next.RouteAsync(context);
                }
            finally
                {
                if (!context.IsHandled)
                    {
                    context.RouteData = oldRouteData;
                    }

                }
            }

      
        }
  public void Configure(IApplicationBuilder app)
            {
            app.UseMvc(routes =>

            {
                //加入模板 默認http://http://localhost/Home/Index
                //  routes.Routes.Add(new MyTemplateRoute(routes));


          
                routes.MapRoute("default", "{controller}/{action}");
                //加入路由處理 默認http://http://localhost/Home/Index
                routes.Routes.Add(new DefaultRoute(routes.DefaultHandler));

            });
            }

實現IRouteConstraint約束

  public class DateConstraint : IRouteConstraint
        {
        public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection)
            {
            return values["controller"] == "Home";
            }
        }
  public void Configure(IApplicationBuilder app)
            {
            app.UseMvc(routes =>

            {
                //加入模板 默認http://http://localhost/Home/Index
                //  routes.Routes.Add(new MyTemplateRoute(routes));


          
                //routes.MapRoute("default", "{controller}/{action}");
                ////加入路由處理 默認http://http://localhost/Home/Index
                //routes.Routes.Add(new DefaultRoute(routes.DefaultHandler));

                //加入約束
                routes.MapRoute(name: "TestRoute", template: "{*constraints}", defaults: new { controller = "Home", action = "Index" }, constraints: new { constraint = new DateConstraint() });

            });
            }

路由特性

public class HomeController : Controller
        {


        //PUT   http://localhost/AB
        [AcceptVerbs("PUT", Route = "AB")]
        // Patch  http://localhost/AB
        [HttpPatch("AB")]
        //PUT   http://localhost/Home/AB
        [AcceptVerbs("PUT", Route = "Home/AB")]
        //Patch   http://localhost/Home/AB
        [HttpPatch("Home/Ab")]

        // ABC 動作 可以被以下地址訪問
        //PUT   http://localhost/AB
        // Patch  http://localhost/AB
        //PUT   http://localhost/Home/AB
        //Patch   http://localhost/Home/AB
        public IActionResult  ABC()
            {

            return Content("1");
            }
        }


    }

 RouteConstraintAttribute 路由約束

   public class CountrySpecificAttribute : RouteConstraintAttribute
        {
        public CountrySpecificAttribute(string countryCode)
            : base("country", countryCode, blockNonAttributedActions: true)
            {
            }
        }

應用在控制上

添加路由條目

  routes.MapRoute(
                  "products",
                  "Products/{country}/{action}",
                  defaults: new { controller = "Products" })yu

運行截圖

 

Area 

 

//區域名 
[Area("Admin")]
//路由 [Route(
"[area]/Users")] public class UserManagementController : Controller { [HttpGet("All")] public IActionResult ListUsers() { return Content("11"); } }

 

添加路由條目

    routes.MapRoute("areaRoute",
                               "{area:exists}/{controller}/{action}",
                               new { controller = "Home", action = "Index" });

 


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 AutoPoster 的頭像
    AutoPoster

    互聯網 - 大數據

    AutoPoster 發表在 痞客邦 留言(0) 人氣()