/// <summary>Maps a content route to the route collection.</summary> /// <param name="routes">The route collection to extend.</param> /// <param name="name">The name of this route.</param> /// <param name="engine">The N2 Engine instance used by the content route.</param> /// <returns>The added content route instance.</returns> public static ContentRoute MapContentRoute <T>(this AreaRegistrationContext arc) where T : ContentItem { var state = arc.State as AreaRegistrationState; if (state == null) { throw new ArgumentException("The area registration context didn't contain an AreaRegistrationState.", "arc"); } if (state.Engine == null) { throw new ArgumentException("The area registration state an IEngine.", "arc"); } var routeHandler = new MvcRouteHandler(); var controllerMapper = state.Engine.Resolve <IControllerMapper>(); var innerRoute = new Route("{area}/{controller}/{action}", new RouteValueDictionary(new { action = "Index" }), new RouteValueDictionary(), new RouteValueDictionary(new { engine = state.Engine, area = arc.AreaName }), routeHandler); var cr = new ContentRoute <T>(state.Engine, routeHandler, controllerMapper, innerRoute); arc.Routes.Add(arc.AreaName + "_" + typeof(T).FullName, cr); return(cr); }
public IRouteHandler CreateRouteHandler(IOwinContext context, RouteResolveResult resolveResult) { context.Request.RouteValues = resolveResult.RouteValues; IRouteHandler handler = new MvcRouteHandler(resolveResult); return(handler); }
public SubdomainRouteHandler(IApplicationBuilder app) { System.Console.WriteLine("in the ctors"); this.m_routeHandler = app.ApplicationServices. GetRequiredService <MvcRouteHandler>(); }
public IEnumerable <RouteDescriptor> GetRoutes() { const string areaName = "Downplay.Theory.Identity"; var emptyConstraints = new RouteValueDictionary(); var directoryRouteValueDictionary = new RouteValueDictionary { { "area", areaName } }; var mvcRouteHandler = new MvcRouteHandler(); // TODO: Allow multiple directories under different route slugs return(new[] { new RouteDescriptor { Route = new Route( "Directory", new RouteValueDictionary { { "area", areaName }, { "controller", "Directory" }, { "action", "Directory" } }, emptyConstraints, directoryRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route( "Directory/PostalCodeSearch", new RouteValueDictionary { { "area", areaName }, { "controller", "Directory" }, { "action", "PostalCodeSearch" } }, emptyConstraints, directoryRouteValueDictionary, mvcRouteHandler) } }); }
public async Task RouteHandler_WritesDiagnostic_ActionSelected() { // Arrange var listener = new TestDiagnosticListener(); var context = CreateRouteContext(diagnosticListener: listener); context.RouteData.Values.Add("tag", "value"); var handler = new MvcRouteHandler(); await handler.RouteAsync(context); // Act await context.Handler(context.HttpContext); // Assert Assert.NotNull(listener.BeforeAction?.ActionDescriptor); Assert.NotNull(listener.BeforeAction?.HttpContext); var routeValues = listener.BeforeAction?.RouteData?.Values; Assert.NotNull(routeValues); Assert.Equal(1, routeValues.Count); Assert.Contains(routeValues, kvp => kvp.Key == "tag" && string.Equals(kvp.Value, "value")); }
public async Task RouteAsync_FailOnNoAction_LogsCorrectValues() { // Arrange var sink = new TestSink(); var loggerFactory = new TestLoggerFactory(sink, enabled: true); var mockActionSelector = new Mock <IActionSelector>(); mockActionSelector .Setup(a => a.Select(It.IsAny <RouteContext>())) .Returns <ActionDescriptor>(null); var context = CreateRouteContext( actionSelector: mockActionSelector.Object, loggerFactory: loggerFactory); var handler = new MvcRouteHandler(); var expectedMessage = "No actions matched the current request"; // Act await handler.RouteAsync(context); // Assert Assert.Empty(sink.Scopes); Assert.Single(sink.Writes); Assert.Equal(expectedMessage, sink.Writes[0].State?.ToString()); }
public async Task RouteHandler_Success_LogsCorrectValues() { // Arrange var sink = new TestSink(); var loggerFactory = new TestLoggerFactory(sink, enabled: true); var displayName = "A.B.C"; var actionDescriptor = new Mock <ActionDescriptor>(); actionDescriptor .SetupGet(ad => ad.DisplayName) .Returns(displayName); var context = CreateRouteContext(actionDescriptor: actionDescriptor.Object, loggerFactory: loggerFactory); var handler = new MvcRouteHandler(); await handler.RouteAsync(context); // Act await context.Handler(context.HttpContext); // Assert Assert.Single(sink.Scopes); Assert.Equal(displayName, sink.Scopes[0].Scope?.ToString()); Assert.Equal(2, sink.Writes.Count); Assert.Equal($"Executing action {displayName}", sink.Writes[0].State?.ToString()); // This message has the execution time embedded, which we don't want to verify. Assert.StartsWith($"Executed action {displayName} ", sink.Writes[1].State?.ToString()); }
public IEnumerable <RouteDescriptor> GetRoutes() { const string areaName = "FeaturedItemSlider"; var emptyConstraints = new RouteValueDictionary(); var sliderRouteValueDictionary = new RouteValueDictionary { { "area", areaName } }; var mvcRouteHandler = new MvcRouteHandler(); return(new[] { new RouteDescriptor { Route = new Route( "Admin/FeaturedItems/{groupName}", new RouteValueDictionary { { "area", areaName }, { "controller", "Admin" }, { "action", "Items" }, { "groupName", "" } }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route( "Admin/FeaturedItemGroups", new RouteValueDictionary { { "area", areaName }, { "controller", "Admin" }, { "action", "Groups" } }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) } }); }
private static IRouteHandler GetInstanceOfRouteHandler(RouteConfigElement route) { IRouteHandler routeHandler; if (string.IsNullOrEmpty(route.RouteHandlerType)) { routeHandler = new MvcRouteHandler(); } else { try { Type routeHandlerType = Type.GetType(route.RouteHandlerType); routeHandler = Activator.CreateInstance(routeHandlerType) as IRouteHandler; } catch (Exception e) { throw new ApplicationException( string.Format("Can't create an instance of IRouteHandler {0}", route.RouteHandlerType), e); } } return(routeHandler); }
public async Task RouteHandler_RemovesRouteGroupFromRouteValues() { // Arrange var invoker = new Mock <IActionInvoker>(); invoker .Setup(i => i.InvokeAsync()) .Returns(Task.FromResult(true)); var invokerFactory = new Mock <IActionInvokerFactory>(); invokerFactory .Setup(f => f.CreateInvoker(It.IsAny <ActionContext>())) .Returns <ActionContext>((c) => { return(invoker.Object); }); var context = CreateRouteContext(invokerFactory: invokerFactory.Object); var handler = new MvcRouteHandler(); var originalRouteData = context.RouteData; originalRouteData.Values.Add(TreeRouter.RouteGroupKey, "/Home/Test"); // Act await handler.RouteAsync(context); // Assert Assert.Same(originalRouteData, context.RouteData); Assert.False(context.RouteData.Values.ContainsKey(TreeRouter.RouteGroupKey)); }
public IEnumerable<RouteDescriptor> GetRoutes() { const string areaName = "ContentSlider"; var emptyConstraints = new RouteValueDictionary(); var sliderRouteValueDictionary = new RouteValueDictionary { { "area", areaName } }; var mvcRouteHandler = new MvcRouteHandler(); return new[] { new RouteDescriptor { Name = "ContentSlider.FeaturedItems" , Route = new Route( "Admin/FeaturedItems", new RouteValueDictionary { {"area", areaName}, {"controller", "Admin"}, {"action", "Items"} }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route( "Admin/FeaturedItemGroups", new RouteValueDictionary { {"area", areaName}, {"controller", "Admin"}, {"action", "Groups"} }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) } }; }
private static RouteBase CreateRoute(string url, object defaults) { IRouteHandler routeHandler = new MvcRouteHandler(); #if DEBUG routeHandler = new CustomRouteHandler(); #endif return new Route(url, new RouteValueDictionary(defaults), routeHandler); }
public HostRouteData(IApplicationBuilder app) { this.Routers.Clear(); MvcRouteHandler rh = app.ApplicationServices. GetRequiredService <MvcRouteHandler>(); this.Routers.Add(new CustomRouteHandler(app)); }
public Task RouteAsync(RouteContext context) { var handler = new MvcRouteHandler(); context.RouteData.Values.Add("controller", "Home"); context.RouteData.Values.Add("action", "Index"); return(handler.RouteAsync(context)); }
public ActionResult Index(string name = "defalut") { MvcRouteHandler mvchandler=new MvcRouteHandler(); // MvcHandler mhandler=new MvcHandler(); // PageRouteHandler handlerpage=new PageRouteHandler(); var rq= this.RouteData.GetRequiredString("name"); var dk = this.RouteData.DataTokens["name1"]; // var path = this.RouteData.Route.GetVirtualPath(); return Content("你好:" + name); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { IRouteHandler handler = new MvcRouteHandler(); var vals = requestContext.RouteData.Values; if (vals["language"] == null) { vals["language"] = "pt"; } return(handler.GetHttpHandler(requestContext)); }
private RouteData createRouteData(string action, string controller) { MvcRouteHandler mvcHandler = new MvcRouteHandler(new DefaultControllerFactory()); var data = new RouteData(this, mvcHandler); data.Values["action"] = action; //this is the value that will get passed to the ControllerFactory by MVC data.Values["controller"] = controller; return(data); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { IRouteHandler handler = new MvcRouteHandler(); var vals = requestContext.RouteData.Values; if(String.IsNullOrEmpty(vals["controller"]) { // fetch action and controller from database vals["controller"] = dbcontroller; vals["action"] = dbaction } return handler.GetHttpHandler(requestContext); }
public override RouteData GetRouteData(HttpContextBase httpContext) { if (httpContext.Request.QueryString.AllKeys.Contains("controller") && httpContext.Request.QueryString.AllKeys.Contains("action")) { string controller = httpContext.Request.QueryString["controller"]; string action = httpContext.Request.QueryString["action"]; IRouteHandler routeHandler=new MvcRouteHandler(); return new RouteData(controller,action,routeHandler); } return null; }
private static RequestContext GetRequestContext(StubContainerProvider containerProvider) { var handler = new MvcRouteHandler(); var route = new Route("yadda", handler) { DataTokens = new RouteValueDictionary {{"IContainerProvider", containerProvider}} }; var httpContext = new StubHttpContext(); var routeData = route.GetRouteData(httpContext); return new RequestContext(httpContext, routeData); }
public DefaultReusableRouteHandler(MvcRouteHandler target, IActionDescriptorCollectionProvider actionProvider, PipelineDecisionTree pipelineDecisionTree, IOptions <ReusableMvcOptions> options) { _target = target; _pipelineDecisionTree = pipelineDecisionTree; _options = options; _controllerActionUris = actionProvider.ActionDescriptors.Items.Cast <ControllerActionDescriptor>() .GroupBy(t => t.ControllerTypeInfo.FullName) .ToDictionary(t => t.Key, t => t.Select(x => (x.AttributeRouteInfo != null ? x.AttributeRouteInfo.Template : $"{t.Key}/{x.ActionName}").Trim('/')), StringComparer.OrdinalIgnoreCase); }
public void ToUrl(string url, object values) { //创建路由处理程序实例 var routeHandler = new MvcRouteHandler(); //创建路由数据 var routeData = new RouteData(new Route(url, routeHandler), routeHandler); //添加路由参数/值 foreach (var pair in new RouteValueDictionary(values)) { routeData.Values[pair.Key] = pair.Value; } Route(routeData); }
public void GetHttpHandlerThrowsIfTheRouteValuesDoesNotIncludeAControllerName() { // Arrange var httpContext = new Mock <HttpContextBase>(); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext.Object, routeData); IRouteHandler routeHandler = new MvcRouteHandler(); // Act & Assert Assert.Throws <InvalidOperationException>( () => routeHandler.GetHttpHandler(requestContext), "The matched route does not include a 'controller' route value, which is required." ); }
public void GetHttpHandlerReturnsMvcHandlerWithRouteData() { // Arrange RequestContext context = new RequestContext(new Mock <HttpContextBase>().Object, new RouteData()); IRouteHandler rh = new MvcRouteHandler(); // Act IHttpHandler httpHandler = rh.GetHttpHandler(context); // Assert MvcHandler h = httpHandler as MvcHandler; Assert.IsNotNull(h, "The handler should be a valid MvcHandler instance"); Assert.AreEqual <RequestContext>(context, h.RequestContext); }
private static RequestContext GetRequestContext(IWorkContextAccessor workContextAccessor) { var handler = new MvcRouteHandler(); var route = new Route("yadda", handler) { DataTokens = new RouteValueDictionary { { "IWorkContextAccessor", workContextAccessor } } }; var httpContext = new StubHttpContext(); var routeData = route.GetRouteData(httpContext); return(new RequestContext(httpContext, routeData)); }
public async Task Execute(TextWriter writer) { var routeContext = new RouteContext(_httpContext) { RouteData = new RouteData(_routeData) }; // Save current context var currentOutputStream = _httpContext.Response.Body; var currentRouteData = routeContext.RouteData; using (var outputStream = new MemoryStream()) { // Setup context _httpContext.Response.Body = outputStream; routeContext.RouteData.Values["controller"] = _controller; routeContext.RouteData.Values["action"] = _action; var handler = new MvcRouteHandler(); try { // Invoke controller await handler.RouteAsync(routeContext); outputStream.Position = 0; using (var reader = new StreamReader(outputStream)) { var output = await reader.ReadToEndAsync(); await writer.WriteLineAsync(output); } routeContext.IsHandled = true; } finally { // Restore context routeContext.RouteData = currentRouteData; _httpContext.Response.Body = currentOutputStream; } } }
public async Task RouteHandler_WritesDiagnostic_ActionInvoked() { // Arrange var listener = new TestDiagnosticListener(); var context = CreateRouteContext(diagnosticListener: listener); var handler = new MvcRouteHandler(); await handler.RouteAsync(context); // Act await context.Handler(context.HttpContext); // Assert Assert.NotNull(listener.AfterAction?.ActionDescriptor); Assert.NotNull(listener.AfterAction?.HttpContext); }
public IEnumerable <RouteDescriptor> GetRoutes() { string areaName = "Orchard.ContentTree"; var emptyConstraints = new RouteValueDictionary(); var sliderRouteValueDictionary = new RouteValueDictionary { { "area", areaName } }; var mvcRouteHandler = new MvcRouteHandler(); return(new[] { new RouteDescriptor { Priority = 0, Route = new Route( "Admin/ContentTree", new RouteValueDictionary { { "area", areaName }, { "action", "ContentTree" }, { "controller", "Admin" }, }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Priority = 0, Route = new Route( "Admin/ContentTreeAsync", new RouteValueDictionary { { "area", areaName }, { "action", "ContentTreeAsync" }, { "controller", "Admin" }, }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route( "Admin/ContentTree/SaveActions", new RouteValueDictionary { { "area", areaName }, { "action", "SaveActions" }, { "controller", "Admin" }, }, emptyConstraints, sliderRouteValueDictionary, mvcRouteHandler) } }); }
private IntraRouteAttribute(string url, string name, HttpVerbs?verbs, RoutePriority priority, RouteHandler handler) { Url = url.ToLower(); Name = name; AcceptVerbs = verbs; Priority = priority; switch (handler) { case RouteHandler.Mvc: Handler = new MvcRouteHandler(); break; default: Handler = new MvcRouteHandler(); break; } }
private static ContentRoute MapContentRoute(this RouteCollection routes, string name, IEngine engine, string url, object defaults, object constraints, string[] namespaces) { var rh = new MvcRouteHandler(); Route innerRoute = new Route(url, rh); innerRoute.Defaults = new RouteValueDictionary(defaults); innerRoute.Constraints = new RouteValueDictionary(constraints); innerRoute.DataTokens = new RouteValueDictionary(); if ((namespaces != null) && (namespaces.Length > 0)) { innerRoute.DataTokens["Namespaces"] = namespaces; } var cr = new ContentRoute(engine, rh, null, innerRoute); routes.Add(name, cr); return(cr); }
public void GetHttpHandlerAsksControllerFactoryForSessionBehaviorOfController() { // Arrange var httpContext = new Mock <HttpContextBase>(); var routeData = new RouteData(); routeData.Values["controller"] = "controllerName"; var requestContext = new RequestContext(httpContext.Object, routeData); var controllerFactory = new Mock <IControllerFactory>(); controllerFactory.Setup(f => f.GetControllerSessionBehavior(requestContext, "controllerName")) .Returns(SessionStateBehavior.ReadOnly) .Verifiable(); IRouteHandler routeHandler = new MvcRouteHandler(controllerFactory.Object); // Act routeHandler.GetHttpHandler(requestContext); // Assert controllerFactory.Verify(); httpContext.Verify(c => c.SetSessionStateBehavior(SessionStateBehavior.ReadOnly)); }
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); var mvcRouteHandler = new MvcRouteHandler(); routes.Add("Empty", new Route( "", new RouteValueDictionary(new { controller = "Chat", action = "Index" }), mvcRouteHandler ) ); routes.Add("Auth", new Route( "{action}", new RouteValueDictionary(new { controller = "Auth" }), mvcRouteHandler ) ); }
public void GetHttpHandlerReturnsMvcHandlerWithRouteData() { // Arrange var routeData = new RouteData(); routeData.Values["controller"] = "controllerName"; var context = new RequestContext(new Mock <HttpContextBase>().Object, routeData); var controllerFactory = new Mock <IControllerFactory>(); controllerFactory.Setup(f => f.GetControllerSessionBehavior(context, "controllerName")) .Returns(SessionStateBehavior.Default) .Verifiable(); IRouteHandler rh = new MvcRouteHandler(controllerFactory.Object); // Act IHttpHandler httpHandler = rh.GetHttpHandler(context); // Assert MvcHandler h = httpHandler as MvcHandler; Assert.NotNull(h); Assert.Equal(context, h.RequestContext); }
public IEnumerable<RouteDescriptor> GetRoutes() { const string areaName = "Downplay.Theory.Identity"; var emptyConstraints = new RouteValueDictionary(); var directoryRouteValueDictionary = new RouteValueDictionary { { "area", areaName } }; var mvcRouteHandler = new MvcRouteHandler(); // TODO: Allow multiple directories under different route slugs return new[] { new RouteDescriptor { Route = new Route( "Directory", new RouteValueDictionary { {"area", areaName}, {"controller", "Directory"}, {"action", "Directory"} }, emptyConstraints, directoryRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route( "Directory/PostalCodeSearch", new RouteValueDictionary { {"area", areaName}, {"controller", "Directory"}, {"action", "PostalCodeSearch"} }, emptyConstraints, directoryRouteValueDictionary, mvcRouteHandler) } }; }
public IEnumerable<RouteDescriptor> GetRoutes() { const string areaName = "Orchard.Gallery"; var emptyConstraints = new RouteValueDictionary(); var galleryRouteValueDictionary = new RouteValueDictionary {{"area", areaName}}; var mvcRouteHandler = new MvcRouteHandler(); return new[] { new RouteDescriptor { Route = new Route ( "Contribute/ManagePackageIds", new RouteValueDictionary { {"area", areaName}, {"controller", "ManagePackageIds"}, {"action", "Index"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler) }, new RouteDescriptor { Route = new Route ( "Ratings/AuthorizeUpdate/{nonce}", new RouteValueDictionary { {"area", areaName}, {"controller", "RatingsUpdateAuthorization"}, {"action", "AuthorizeUpdate"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Package/ReportAbuse/{packageId}/{packageVersion}", new RouteValueDictionary { {"area", areaName}, {"controller", "ReportAbuse"}, {"action", "Index"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Package/ContactOwners/{packageId}", new RouteValueDictionary { {"area", areaName}, {"controller", "ContactOwners"}, {"action", "Index"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "ManagePackageOwners/{packageId}", new RouteValueDictionary { {"area", areaName}, {"controller", "ManagePackageOwners"}, {"action", "Index"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "UploadPackageLogoAndScreenshots/{action}/{packageId}/{packageVersion}", new RouteValueDictionary { {"area", areaName}, {"controller", "UploadPackageLogoAndScreenshots"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Contribute/NewSubmission", new RouteValueDictionary { {"area", areaName}, {"controller", "UploadPackage"}, {"action", "Index"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Contribute/{action}", new RouteValueDictionary { {"area", areaName}, {"controller", "Contribute"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/ByAuthor/{authorName}", new RouteValueDictionary { {"area", areaName}, {"controller", "Packages"}, {"action", "ByAuthor"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/ByCategory/{packageType}/{categoryName}", new RouteValueDictionary { {"area", areaName}, {"controller", "Packages"}, {"action", "ByCategory"}, }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/{packageType}/{packageId}", new RouteValueDictionary { {"area", areaName}, {"controller", "Package"}, {"action", "DetailsForId"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/{packageType}/{packageId}/{packageVersion}", new RouteValueDictionary { {"area", areaName}, {"controller", "Package"}, {"action", "DetailsForIdAndVersion"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Package/{action}/{packageId}/{packageVersion}", new RouteValueDictionary { {"area", areaName}, {"controller", "Package"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "Package/Delete", new RouteValueDictionary { {"area", areaName}, {"controller", "Package"}, {"action", "Delete"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor{ Route = new Route ( "PackageAuthentication/{action}/{key}/{packageId}/{packageVersion}", new RouteValueDictionary { {"area", areaName}, {"controller", "PackageAuthentication"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor{ Route = new Route ( "PackageAuthentication/{action}/{key}", new RouteValueDictionary { {"area", areaName}, {"controller", "PackageAuthentication"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/Search", new RouteValueDictionary { {"area", areaName}, {"controller", "Packages"}, {"action", "Search"}, }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "List/{packageType}", new RouteValueDictionary { {"area", areaName}, {"controller", "Packages"}, {"action", "List"}, }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "PackageCategories/{packageType}", new RouteValueDictionary { {"area", areaName}, {"controller", "PackageCategories"}, {"action", "Categories"} }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, new RouteDescriptor { Route = new Route ( "SearchResults", new RouteValueDictionary { {"area", areaName}, {"controller", "PackageSearch"}, {"action", "Index"}, }, emptyConstraints, galleryRouteValueDictionary, mvcRouteHandler ) }, }; }
public DefaultShellRouteBuilder(IServiceProvider serviceProvider) { Routes = new List <IRouter>(); DefaultHandler = new MvcRouteHandler(); ServiceProvider = serviceProvider; }
public SubdomainRoute(string controller, string defaultAction, MvcRouteHandler mvcRouteHandler) { _controller = controller; _defaultAction = defaultAction; _mvcRouteHandler = mvcRouteHandler; }
/// <summary> /// Gets the instance of route handler. /// </summary> /// <param name="route">The route.</param> /// <returns></returns> private static IRouteHandler GetInstanceOfRouteHandler(RouteConfigElement route) { IRouteHandler routeHandler; if (string.IsNullOrEmpty(route.RouteHandlerType)) routeHandler = new MvcRouteHandler(); else { try { Type routeHandlerType = Type.GetType(route.RouteHandlerType); routeHandler = Activator.CreateInstance(routeHandlerType) as IRouteHandler; } catch (Exception e) { throw new ApplicationException( string.Format("Can't create an instance of IRouteHandler {0}", route.RouteHandlerType), e); } } return routeHandler; }
private static void Config() { HttpRuntime.Cache.Insert(ConfigFilePathDependencyKey, "", new CacheDependency(configFilePath), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, AppInfoCenterConfigFileUpdated); routes.Clear(); routes.RouteExistingFiles = true; action(routes); //Routes.Add("w1", new Route("{page}.aspx", new AspxRouteHandler())); //Routes.Add("w2", new Route("{folder}/{page}.aspx", new AspxRouteHandler())); //Routes.Add("w3", new Route("{page}.ashx", new AspxRouteHandler())); //Routes.Add("w4", new Route("{folder}/{page}.ashx", new AspxRouteHandler())); //Routes.Add("w5", new Route("{page}.asmx", new AspxRouteHandler())); //Routes.Add("w6", new Route("{folder}/{page}.asmx", new AspxRouteHandler())); var config = XDocument.Load(configFilePath); using (routes.GetWriteLock()) { var ignoreUrls = config.Descendants("routeTable").Descendants("ignore").Select(item => item.Attribute("url").Value).ToList(); ignoreUrls.ForEach(url => routes.IgnoreRoute(url)); var addItems = config.Descendants("routeTable").Descendants("add").Select(item => new { Name = item.Attribute("name").Value, Url = item.Attribute("url").Value, Engine = item.Attribute("engine") == null ? "mvc" : item.Attribute("engine").Value.ToLower(), Defaults = item.Descendants("defaults").Elements().Select(sub => new { Name = sub.Name.ToString(), DefaultValue = sub.Value }).ToList(), Constraints = item.Descendants("constraints").Elements().Select(sub => new { Name = sub.Name.ToString(), Pattern = sub.Value }).ToList() }).ToList(); foreach (var item in addItems) { var defaults = new RouteValueDictionary(); foreach (var d in item.Defaults) { if (!defaults.ContainsKey(d.Name)) { if (string.IsNullOrEmpty(d.DefaultValue)) { defaults.Add(d.Name, UrlParameter.Optional); } else { defaults.Add(d.Name, d.DefaultValue); } } } var constraints = new RouteValueDictionary(); foreach (var d in item.Constraints) if (!constraints.ContainsKey(d.Name)) constraints.Add(d.Name, d.Pattern); if (routes[item.Name] == null) { IRouteHandler handler = new MvcRouteHandler(); if (item.Engine != "mvc") handler = new AspxRouteHandler(); routes.Add(item.Name, new Route(item.Url, defaults, constraints, handler)); } } var removeItems = config.Descendants("routeTable").Descendants("remove").Select(item => item.Attribute("name").Value).ToList(); removeItems.ForEach(name => { if (routes[name] != null) routes.Remove(routes[name]); }); } }
public static void AutoRegisterRoutes(RouteCollection routes, Type forceController = null) { var assembly = Assembly.GetExecutingAssembly(); var controllers = forceController == null ? assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)) && !t.Name.StartsWith("T4MVC_")) : new List<Type> { forceController }; var currentRoutes = new Dictionary<string, bool>(); var routeHandler = new MvcRouteHandler(); foreach (var controller in controllers) { var controllerName = controller.Name.Replace("Controller", string.Empty); var actions = controller.GetMethods() .Where(m => m.ReturnType.IsSubclassOf(typeof(ActionResult)) || m.ReturnType == typeof(ActionResult)) .Where(m => !m.GetCustomAttributes(typeof(NonActionAttribute), true).Any()) .Where(m => m.IsPublic); foreach (var action in actions) { var isPartialAction = action.GetCustomAttributes(typeof (DefaultRoutingAttribute), true).Any(); string route; if (!isPartialAction) { var resourceName = string.Format("{0}_{1}", controllerName, action.Name); route = Resources.Routes.ResourceManager.GetString(resourceName); if (!currentRoutes.ContainsKey(resourceName)) currentRoutes.Add(resourceName, route == null); if (route == null) continue; } else route = string.Format("{0}/{1}", controllerName, action.Name); var routeDictionary = new RouteValueDictionary { {"controller", controllerName}, {"action", action.Name}, {"area", string.Empty} }; if (!action.GetCustomAttributes(typeof(HttpPostAttribute), true).Any()) { var parameters = action.GetParameters(); var parametersString = new StringBuilder(); foreach (var parameter in parameters.Where(p => !p.GetCustomAttributes(typeof(QueryParameterAttribute), true).Any())) { if(!(parameter.DefaultValue is DBNull)) routeDictionary.Add(parameter.Name, UrlParameter.Optional); parametersString.Append("/{" + parameter.Name + "}"); } route += parametersString.ToString(); } routes.Add(new Route(route, routeDictionary, routeHandler)); } } var missingRoutes = currentRoutes.Where(kvp => kvp.Value).ToList(); if (missingRoutes.Any()) { var missingRoutesInfo = new StringBuilder(); foreach (var missingRoute in missingRoutes) missingRoutesInfo.AppendLine(missingRoute.Key); throw new Exception("Missing routes: " + Environment.NewLine + missingRoutesInfo); } var resourceSet = Resources.Routes.ResourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, false); var resourcesDictionary = resourceSet.Cast<DictionaryEntry>().ToDictionary(entry => (string) entry.Key, entry => (string) entry.Value); resourceSet.Close(); if (forceController == null) { foreach (var entry in resourcesDictionary) { if (!currentRoutes.ContainsKey(entry.Key)) throw new Exception("Unnecessary resource key: " + entry.Key); if (resourcesDictionary.Count(kvp => entry.Key == kvp.Key) > 1) throw new Exception("Route duplicated: " + entry.Value); } } }
public DefaultShellRouteBuilder(IServiceProvider serviceProvider) { Routes = new List<IRouter>(); DefaultHandler = new MvcRouteHandler(); ServiceProvider = serviceProvider; }
public NamedRoute(string name, string displayName, string url, MvcRouteHandler routeHandler) : base(url, routeHandler) { _name = name; _displayName = displayName; }
public FileUploadRoute(MvcRouteHandler handler, string virtualPath, string controller) { Handler = handler ?? throw new ArgumentNullException(nameof(handler)); VirtualPath = virtualPath ?? throw new ArgumentNullException(nameof(virtualPath)); Controller = controller ?? throw new ArgumentNullException(nameof(controller)); }