public void ProcessRequestWithDisabledServerHeaderOnlyCallsExecute() { bool oldResponseHeaderValue = MvcHandler.DisableMvcResponseHeader; try { // Arrange MvcHandler.DisableMvcResponseHeader = true; Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); RouteData rd = new RouteData(); rd.Values.Add("controller", "foo"); RequestContext requestContext = new RequestContext(contextMock.Object, rd); MvcHandler mvcHandler = new MvcHandler(requestContext); Mock<ControllerBase> controllerMock = new Mock<ControllerBase>(); controllerMock.Protected().Expect("Execute", requestContext).Verifiable(); ControllerBuilder cb = new ControllerBuilder(); Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>(); controllerFactoryMock.Expect(o => o.CreateController(requestContext, "foo")).Returns(controllerMock.Object); controllerFactoryMock.Expect(o => o.ReleaseController(controllerMock.Object)); cb.SetControllerFactory(controllerFactoryMock.Object); mvcHandler.ControllerBuilder = cb; // Act mvcHandler.ProcessRequest(contextMock.Object); // Assert controllerMock.Verify(); } finally { MvcHandler.DisableMvcResponseHeader = oldResponseHeaderValue; } }
public void ProcessRequestAddsServerHeaderCallsExecute() { // Arrange Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); contextMock.ExpectMvcVersionResponseHeader().Verifiable(); RouteData rd = new RouteData(); rd.Values.Add("controller", "foo"); RequestContext requestContext = new RequestContext(contextMock.Object, rd); MvcHandler mvcHandler = new MvcHandler(requestContext); Mock<ControllerBase> controllerMock = new Mock<ControllerBase>(); controllerMock.Protected().Setup("Execute", requestContext).Verifiable(); ControllerBuilder cb = new ControllerBuilder(); Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>(); controllerFactoryMock.Setup(o => o.CreateController(requestContext, "foo")).Returns(controllerMock.Object); controllerFactoryMock.Setup(o => o.ReleaseController(controllerMock.Object)); cb.SetControllerFactory(controllerFactoryMock.Object); mvcHandler.ControllerBuilder = cb; // Act mvcHandler.ProcessRequest(contextMock.Object); // Assert contextMock.Verify(); controllerMock.Verify(); }
public void ProcessRequestRemovesOptionalParametersFromRouteValueDictionary() { // Arrange Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); contextMock.ExpectMvcVersionResponseHeader(); RouteData rd = new RouteData(); rd.Values.Add("controller", "foo"); rd.Values.Add("optional", UrlParameter.Optional); RequestContext requestContext = new RequestContext(contextMock.Object, rd); MvcHandler mvcHandler = new MvcHandler(requestContext); Mock<ControllerBase> controllerMock = new Mock<ControllerBase>(); controllerMock.Protected().Setup("Execute", requestContext).Verifiable(); ControllerBuilder cb = new ControllerBuilder(); Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>(); controllerFactoryMock.Setup(o => o.CreateController(requestContext, "foo")).Returns(controllerMock.Object); controllerFactoryMock.Setup(o => o.ReleaseController(controllerMock.Object)); cb.SetControllerFactory(controllerFactoryMock.Object); mvcHandler.ControllerBuilder = cb; // Act mvcHandler.ProcessRequest(contextMock.Object); // Assert controllerMock.Verify(); Assert.IsFalse(rd.Values.ContainsKey("optional"), "Optional value should have been removed."); }
public void Invoke(ControllerContext context) { RouteData rd = new RouteData(context.RouteData.Route, context.RouteData.RouteHandler); foreach (var pair in RouteValues) rd.Values.Add(pair.Key, pair.Value); IHttpHandler handler = new MvcHandler(new RequestContext(context.HttpContext, rd)); handler.ProcessRequest(System.Web.HttpContext.Current); }
/// <summary> /// Gets the HTTP handler and redirects output if "routeInfo" is a query string. /// </summary> /// <param name="requestContext">The request which is made to the route handler.</param> /// <returns>A HTTP Handler</returns> public IHttpHandler GetHttpHandler(RequestContext requestContext) { if (HasQueryStringKey("routeInfo", requestContext.HttpContext.Request)) { OutputRouteDiagnostics(requestContext.RouteData, requestContext.HttpContext); } var handler = new MvcHandler(requestContext); return handler; }
public void SetUp() { context = TestsHelper.PrepareRequestContext(); handler = new BlogMvcHandler(context); context.RouteData.Values["controller"] = typeof (Controller); methodInfo = handler.GetType() .GetMethod("ProcessRequest", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof (HttpContextBase)}, null); dummyFactory = MockRepository.GenerateStub<IExtendedControllerFactory>(); ControllerBuilder.Current.SetControllerFactory(dummyFactory); }
public IHttpHandler GetHttpHandler(RequestContext requestContext) { var routeData = requestContext.RouteData; var strValue = routeData.Values["id"].ToString(); Guid guidValue; var action = routeData.Values["action"]; if (Guid.TryParse(strValue, out guidValue) && guidValue != Guid.Empty) { routeData.Values["action"] = action + "Guid"; } var handler = new MvcHandler(requestContext); return handler; }
public void ProcessRequestWithRouteWithoutControllerThrows() { // Arrange Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); contextMock.ExpectMvcVersionResponseHeader().Verifiable(); RouteData rd = new RouteData(); MvcHandler mvcHandler = new MvcHandler(new RequestContext(contextMock.Object, rd)); // Act ExceptionHelper.ExpectException<InvalidOperationException>( delegate { mvcHandler.ProcessRequest(contextMock.Object); }, "The RouteData must contain an item named 'controller' with a non-empty string value."); // Assert contextMock.Verify(); }
public void AttributeRouting_WithInheritance_MethodOverrides(Type derivedController, string path, string expectedAction) { // Arrange var controllerTypes = new[] { derivedController, derivedController.BaseType }; var routes = new RouteCollection(); routes.MapMvcAttributeRoutes(controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal(expectedAction, result.Content); }
protected override void DoRender(HtmlTextWriter output) { var rendering = global::Sitecore.Context.Page.GetRenderingReference(this); if (rendering == null) return; var action = ControllerAction.GetControllerAction(MvcSubLayoutDataProvider.parentId, rendering.RenderingID); if (action == null) return; var httpContext = new HttpContextWrapper(Context); var existingRouteData = RouteTable.Routes.GetRouteData(httpContext); var additionalRouteValues = existingRouteData == null ? new RouteValueDictionary() : existingRouteData.Values ; if (!string.IsNullOrEmpty(DataSource)) { var item = rendering.Database.GetItem(DataSource); if (item != null) { additionalRouteValues["_sitecoreitem"] = item; } } additionalRouteValues["_sitecorerendering"] = rendering; var parameters = WebUtil.ParseUrlParameters(Parameters); foreach (var key in parameters.AllKeys) { additionalRouteValues[key] = parameters[key]; } var routeData = MvcActionHelper.GetRouteData( httpContext, action.ActionName, action.ControllerType.ControllerName, additionalRouteValues, true ); var handler = new MvcHandler(new RequestContext(httpContext, routeData)); httpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(handler), output, true /* preserveForm */); }
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { var pro = MvcMiniProfiler.MiniProfiler.Current; using (pro.Step("Custom Router")) { MerchantTribe.Commerce.MerchantTribeApplication MTApp; string fullSlug; using (pro.Step("Determine Store Id")) { fullSlug = (string)(requestContext.RouteData.Values["slug"] ?? string.Empty); fullSlug = fullSlug.ToLowerInvariant() ?? string.Empty; // Application Context MTApp = MerchantTribe.Commerce.MerchantTribeApplication.InstantiateForDataBase(new MerchantTribe.Commerce.RequestContext()); MTApp.CurrentRequestContext.RoutingContext = requestContext; // Determine store id MTApp.CurrentStore = MerchantTribe.Commerce.Utilities.UrlHelper.ParseStoreFromUrl(System.Web.HttpContext.Current.Request.Url, MTApp); } using (pro.Step("Home Page Check")) { // Home page check if (fullSlug == string.Empty) { // Redirect to Sign up if we're multi-store if (MerchantTribe.Commerce.WebAppSettings.IsHostedVersion) { if (MTApp.CurrentStore.StoreName == "www") { requestContext.RouteData.Values["controller"] = "Home"; requestContext.RouteData.Values["area"] = "signup"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler signupHandler = new MvcHandler(requestContext); return signupHandler; } } using (pro.Step("Sending to Home Page Controller")) { // Send to home controller requestContext.RouteData.Values["controller"] = "Home"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler homeHandler = new MvcHandler(requestContext); return homeHandler; } } } // Check for Category/Page Match CategoryUrlMatchData categoryMatchData = IsCategoryMatch(fullSlug, MTApp); if (categoryMatchData.IsFound) { switch (categoryMatchData.SourceType) { case CategorySourceType.ByRules: case CategorySourceType.CustomLink: case CategorySourceType.Manual: requestContext.RouteData.Values["controller"] = "Category"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerCat = new MvcHandler(requestContext); return mvcHandlerCat; case CategorySourceType.DrillDown: requestContext.RouteData.Values["controller"] = "Category"; requestContext.RouteData.Values["action"] = "DrillDownIndex"; System.Web.Mvc.MvcHandler mvcHandlerCatDrill = new MvcHandler(requestContext); return mvcHandlerCatDrill; case CategorySourceType.FlexPage: requestContext.RouteData.Values["controller"] = "FlexPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandler2 = new System.Web.Mvc.MvcHandler(requestContext); return mvcHandler2; case CategorySourceType.CustomPage: requestContext.RouteData.Values["controller"] = "CustomPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerCustom = new MvcHandler(requestContext); return mvcHandlerCustom; } } // Check for Product URL if (IsProductUrl(fullSlug, MTApp)) { requestContext.RouteData.Values["controller"] = "Products"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerProducts = new MvcHandler(requestContext); return mvcHandlerProducts; } // no match on product or category so do a 301 check CheckFor301(fullSlug, MTApp); // If not product, send to FlexPage Controller requestContext.RouteData.Values["controller"] = "FlexPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandler = new System.Web.Mvc.MvcHandler(requestContext); return mvcHandler; } }
public void AttributeRouting_OptionalParametersGetRemoved() { // Arrange var controllerTypes = new[] { typeof(OptionalParameterController) }; var routes = new RouteCollection(); AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes); HttpContextBase context = GetContext("~/Create"); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal("Create()", result.Content); // The request context should be updated to to contain the routedata of the direct route Assert.Equal("{action}/{id}", ((Route)requestContext.RouteData.Route).Url); Assert.Null(requestContext.RouteData.Values["id"]); }
public void AttributeRouting_WithCustomizedRoutePrefixAttribute(string path, string expectedAction) { // Arrange var controllerTypes = new[] { typeof(ControllersWithCustomizedRoutePrefixAttribute.NS1.HomeController), typeof(ControllersWithCustomizedRoutePrefixAttribute.NS2.AccountController), typeof(ControllersWithCustomizedRoutePrefixAttribute.NS3.OtherController), }; var routes = new RouteCollection(); AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal(expectedAction, result.Content); }
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { RedirectOldBVSoftwareDomains(requestContext); MerchantTribe.Commerce.MerchantTribeApplication MTApp; string fullSlug; fullSlug = (string)(requestContext.RouteData.Values["slug"] ?? string.Empty); fullSlug = fullSlug.ToLowerInvariant() ?? string.Empty; // Application Context MTApp = MerchantTribe.Commerce.MerchantTribeApplication.InstantiateForDataBase(new MerchantTribe.Commerce.RequestContext()); MTApp.CurrentRequestContext.RoutingContext = requestContext; // Determine store id MTApp.CurrentStore = MerchantTribe.Commerce.Utilities.UrlHelper.ParseStoreFromUrl(System.Web.HttpContext.Current.Request.Url, MTApp); // Home page check if (fullSlug == string.Empty) { // Redirect to Sign up if we're multi-store if (MerchantTribe.Commerce.WebAppSettings.IsHostedVersion) { if (MTApp.CurrentStore.StoreName == "www") { requestContext.RouteData.Values["controller"] = "Home"; requestContext.RouteData.Values["area"] = "signup"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler signupHandler = new MvcHandler(requestContext); return(signupHandler); } } // Send to home controller requestContext.RouteData.Values["controller"] = "Home"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler homeHandler = new MvcHandler(requestContext); return(homeHandler); } // Check for Category/Page Match CategoryUrlMatchData categoryMatchData = IsCategoryMatch(fullSlug, MTApp); if (categoryMatchData.IsFound) { switch (categoryMatchData.SourceType) { case CategorySourceType.ByRules: case CategorySourceType.CustomLink: case CategorySourceType.Manual: requestContext.RouteData.Values["controller"] = "Category"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerCat = new MvcHandler(requestContext); return(mvcHandlerCat); case CategorySourceType.DrillDown: requestContext.RouteData.Values["controller"] = "Category"; requestContext.RouteData.Values["action"] = "DrillDownIndex"; System.Web.Mvc.MvcHandler mvcHandlerCatDrill = new MvcHandler(requestContext); return(mvcHandlerCatDrill); case CategorySourceType.FlexPage: requestContext.RouteData.Values["controller"] = "FlexPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandler2 = new System.Web.Mvc.MvcHandler(requestContext); return(mvcHandler2); case CategorySourceType.CustomPage: requestContext.RouteData.Values["controller"] = "CustomPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerCustom = new MvcHandler(requestContext); return(mvcHandlerCustom); } } // Check for Product URL if (IsProductUrl(fullSlug, MTApp)) { requestContext.RouteData.Values["controller"] = "Products"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandlerProducts = new MvcHandler(requestContext); return(mvcHandlerProducts); } // no match on product or category so do a 301 check CheckFor301(fullSlug, MTApp); // If not product, send to FlexPage Controller requestContext.RouteData.Values["controller"] = "FlexPage"; requestContext.RouteData.Values["action"] = "Index"; System.Web.Mvc.MvcHandler mvcHandler = new System.Web.Mvc.MvcHandler(requestContext); return(mvcHandler); }
public void AttributeRouting_AmbiguousActions_ThrowsAmbiguousException(Type controllerType, string path) { // Arrange var controllerTypes = new[] { controllerType }; var routes = new RouteCollection(); routes.MapMvcAttributeRoutes(controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); // Act // Bug 1285: Attribute routing with ambiguous actions should throw an AmbiguousMatchException. // This test should fail once that is fixed. Uncomment the line below then. // Assert.Throws<AmbiguousMatchException>(() => handler.ProcessRequest(context)); Assert.DoesNotThrow(() => handler.ProcessRequest(context)); }
public void AttributeRouting_MixedWithGeneralRouting(Type controllerType, string path, string expectedAction) { // Arrange var controllerTypes = new[] { controllerType }; var routes = new RouteCollection(); object defaults = new { controller = controllerType.Name.Substring(0, controllerType.Name.Length - 10) }; routes.Add(new Route("standard/{action}", new RouteValueDictionary(defaults), null)); routes.MapMvcAttributeRoutes(controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); if (expectedAction == null) { // Act & Assert Assert.Throws<HttpException>(() => handler.ProcessRequest(context)); } else { // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal(expectedAction, result.Content); } }
public void AttributeRouting_WithActionNameSelectors(Type controllerType, string path, string expectedAction) { // Arrange var controllerTypes = new[] { controllerType }; var routes = new RouteCollection(); AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); if (expectedAction == null) { // Act & Assert Assert.Throws<HttpException>(() => handler.ProcessRequest(context)); } else { // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal(expectedAction, result.Content); } }
private IHttpAsyncHandler GetHandler(HttpContextBase context, RouteValueDictionary values, out string resultKey) { // Match the incoming URL against the route table RouteData routeData = Routes.GetRouteData(context); // Do nothing if no route found if (routeData == null) { resultKey = null; return null; } resultKey = (string)routeData.DataTokens[Consts.RouteServiceKey]; if (values != null) foreach (var value in values) routeData.Values.Add(value.Key, value.Value); // If a route was found, get an IHttpHandler from the route's RouteHandler IRouteHandler routeHandler = routeData.RouteHandler; //if (routeHandler == null) { // throw new InvalidOperationException( // String.Format( // CultureInfo.CurrentUICulture, // System.Web.SR.GetString(System.Web.SR.UrlRoutingModule_NoRouteHandler))); //} if (routeHandler == null) return null; // This is a special IRouteHandler that tells the routing module to stop processing // routes and to let the fallback handler handle the request. if (routeHandler is StopRoutingHandler) { return null; } RequestContext requestContext = new RequestContext(context, routeData); // Dev10 766875 Adding RouteData to HttpContext context.Request.RequestContext = requestContext; //IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext); var httpHandler = new MvcHandler(requestContext); return httpHandler; //if (httpHandler == null) { // throw new InvalidOperationException( // String.Format( // CultureInfo.CurrentUICulture, // System.Web.SR.GetString(System.Web.SR.UrlRoutingModule_NoHttpHandler), // routeHandler.GetType())); //} //if (httpHandler is UrlAuthFailureHandler) { // if (FormsAuthenticationModule.FormsAuthRequired) { // UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this); // return; // } // else { // throw new HttpException(401, System.Web.SR.GetString(System.Web.SR.Assess_Denied_Description3)); // } //} //// Remap IIS7 to our handler //HttpContext.Current.RemapHandler(httpHandler); }
public void ProcessRequestDisposesControllerIfExecuteThrowsException() { // Arrange Mock<ControllerBase> mockController = new Mock<ControllerBase>(MockBehavior.Strict); mockController.As<IDisposable>().Setup(d => d.Dispose()); // so that Verify can be called on Dispose later mockController.Protected().Setup("Execute", ItExpr.IsAny<RequestContext>()).Throws(new Exception("some exception")); ControllerBuilder builder = new ControllerBuilder(); builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object)); Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); contextMock.ExpectMvcVersionResponseHeader().Verifiable(); RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData()); requestContext.RouteData.Values["controller"] = "fooController"; MvcHandler handler = new MvcHandler(requestContext) { ControllerBuilder = builder }; // Act ExceptionHelper.ExpectException<Exception>( delegate { handler.ProcessRequest(requestContext.HttpContext); }, "some exception"); // Assert mockController.Verify(); contextMock.Verify(); mockController.As<IDisposable>().Verify(d => d.Dispose(), Times.AtMostOnce()); }
/// <summary> /// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that /// the right DataTokens are set. /// </summary> /// <param name="requestContext"></param> /// <param name="postedInfo"></param> private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo) { //set the standard route values/tokens requestContext.RouteData.Values["controller"] = postedInfo.ControllerName; requestContext.RouteData.Values["action"] = postedInfo.ActionName; IHttpHandler handler = new MvcHandler(requestContext); //ensure the controllerType is set if found, meaning it is a plugin, not locally declared if (!postedInfo.Area.IsNullOrWhiteSpace()) { //requestContext.RouteData.Values["controllerType"] = postedInfo.ControllerType; //find the other data tokens for this route and merge... things like Namespace will be included here using (RouteTable.Routes.GetReadLock()) { var surfaceRoute = RouteTable.Routes.OfType<Route>() .SingleOrDefault(x => x.Defaults != null && x.Defaults.ContainsKey("controller") && x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) && x.DataTokens.ContainsKey("area") && x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area)); if (surfaceRoute == null) throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName + " and within the area of " + postedInfo.Area); requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"]; //set the 'Namespaces' token so the controller factory knows where to look to construct it if (surfaceRoute.DataTokens.ContainsKey("Namespaces")) { requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"]; } handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext); } } return handler; }
private void CacheRightsForNode(MvcSiteMapNode mvcNode, MvcHandler handler, string permissionCacheKey) { lock (this.padlock) { // double check if (! permissionCache.ContainsKey(permissionCacheKey)) { // check permission attributes and store required rights in the permission cache. // It's an MvcSiteMapNode, try to figure out the controller class IController controller = ControllerBuilder.Current.GetControllerFactory().CreateController(handler.RequestContext, mvcNode.Controller); Type controllerType = controller.GetType(); // Find all AuthorizeAttributes on the controller class and action method ArrayList controllerAttributes = new ArrayList(controllerType.GetCustomAttributes(typeof(PermissionFilterAttribute), true)); ArrayList actionAttributes = new ArrayList(); MethodInfo[] methods = controllerType.GetType().GetMethods(BindingFlags.Public); foreach (MethodInfo method in methods) { object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true); if ( (attributes.Length == 0 && method.Name == mvcNode.Action) || (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == mvcNode.Action) ) { actionAttributes.AddRange(method.GetCustomAttributes(typeof(PermissionFilterAttribute), true)); } } ICollection<string> rights = new List<string>(); // Attributes found? if (controllerAttributes.Count > 0) { PermissionFilterAttribute attribute = controllerAttributes[0] as PermissionFilterAttribute; foreach (string right in attribute.RightsArray) { if (! rights.Contains(right)) { rights.Add(right); } } } if (actionAttributes.Count > 0) { PermissionFilterAttribute attribute = actionAttributes[0] as PermissionFilterAttribute; foreach (string right in attribute.RightsArray) { if (!rights.Contains(right)) { rights.Add(right); } } } permissionCache.Add(permissionCacheKey, rights.ToArray()); } } }
/// <summary> /// Handles a posted form to an Rebel Url and ensures the correct controller is routed to and that /// the right DataTokens are set. /// </summary> /// <param name="requestContext"></param> /// <param name="postedInfo"></param> /// <param name="renderModel"></param> /// <param name="routeDefinition">The original route definition that would normally be used to route if it were not a POST</param> protected virtual IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo, IRebelRenderModel renderModel, RouteDefinition routeDefinition) { //set the standard route values/tokens requestContext.RouteData.Values["controller"] = postedInfo.ControllerName; requestContext.RouteData.Values["action"] = postedInfo.ActionName; requestContext.RouteData.DataTokens["area"] = postedInfo.Area; IHttpHandler handler = new MvcHandler(requestContext); //ensure the surface id is set if found, meaning it is a plugin, not locally declared if (postedInfo.SurfaceId != default(Guid)) { requestContext.RouteData.Values["surfaceId"] = postedInfo.SurfaceId.ToString("N"); //find the other data tokens for this route and merge... things like Namespace will be included here using (RouteTable.Routes.GetReadLock()) { var surfaceRoute = RouteTable.Routes.OfType<Route>() .Where(x => x.Defaults != null && x.Defaults.ContainsKey("surfaceId") && x.Defaults["surfaceId"].ToString() == postedInfo.SurfaceId.ToString("N")) .SingleOrDefault(); if (surfaceRoute == null) throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for id " + postedInfo.SurfaceId); //set the 'Namespaces' token so the controller factory knows where to look to construct it if (surfaceRoute.DataTokens.ContainsKey("Namespaces")) { requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"]; } handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext); } } //store the original URL this came in on requestContext.RouteData.DataTokens["rebel-item-url"] = requestContext.HttpContext.Request.Url.AbsolutePath; //store the original route definition requestContext.RouteData.DataTokens["rebel-route-def"] = routeDefinition; return handler; }
public void ProcessRequestDisposesControllerIfExecuteDoesNotThrowException() { // Arrange Mock<ControllerBase> mockController = new Mock<ControllerBase>(); mockController.Protected().Expect("Execute", ItExpr.IsAny<RequestContext>()).Verifiable(); mockController.As<IDisposable>().Expect(d => d.Dispose()).AtMostOnce().Verifiable(); ControllerBuilder builder = new ControllerBuilder(); builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object)); Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>(); Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>(); responseMock.Expect(r => r.AppendHeader(MvcHandler.MvcVersionHeaderName, "1.0")).Verifiable(); contextMock.Expect(c => c.Response).Returns(responseMock.Object); RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData()); requestContext.RouteData.Values["controller"] = "fooController"; MvcHandler handler = new MvcHandler(requestContext) { ControllerBuilder = builder }; // Act handler.ProcessRequest(requestContext.HttpContext); // Assert mockController.Verify(); responseMock.Verify(); }
/// <summary> /// Executes controller based on route data. /// </summary> /// <param name="context"></param> /// <param name="routeData"></param> /// <returns></returns> private async Task ExecuteController(HttpContext context, RouteData routeData) { var wrapper = new HttpContextWrapper(context); MvcHandler handler = new MvcHandler(new RequestContext(wrapper, routeData)); IHttpAsyncHandler asyncHandler = ((IHttpAsyncHandler)handler); await Task.Factory.FromAsync(asyncHandler.BeginProcessRequest, asyncHandler.EndProcessRequest, context, null); }
public override void Render(ViewContext ctx, Include include) { //TODO: do we need to clone routedata? ctx.RouteData.Values["controller"] = Controller; ctx.RouteData.Values["action"] = Action; ctx.RouteData.Values["include"] = include; ctx.RouteData.Values["widgetName"] = this.Name; IHttpHandler handler = new MvcHandler(ctx.RequestContext); handler.ProcessRequest(System.Web.HttpContext.Current); }
private static RequestContext GetRequestContext() { Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); RouteData routeData = new RouteData(); routeData.Values["controller"] = "home"; RequestContext requestContext = new RequestContext(mockHttpContext.Object, routeData); IHttpHandler currentHttpHandler = new MvcHandler(requestContext); mockHttpContext.Expect(o => o.Handler).Returns(currentHttpHandler); mockHttpContext.Expect(o => o.Items).Returns(new Hashtable()); return requestContext; }
public void AttributeRouting_MethodOverloads_WithDifferentActionNames(Type controllerType, string path, string expectedAction) { // Arrange var controllerTypes = new[] { controllerType }; var routes = new RouteCollection(); AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); // Act handler.ProcessRequest(context); // Assert ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]); Assert.Equal(expectedAction, result.Content); }
/// <summary> /// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that /// the right DataTokens are set. /// </summary> /// <param name="requestContext"></param> /// <param name="postedInfo"></param> /// <param name="routeDefinition">The original route definition that would normally be used to route if it were not a POST</param> private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo, RouteDefinition routeDefinition) { var standardArea = Umbraco.Core.Configuration.GlobalSettings.UmbracoMvcArea; //set the standard route values/tokens requestContext.RouteData.Values["controller"] = postedInfo.ControllerName; requestContext.RouteData.Values["action"] = postedInfo.ActionName; requestContext.RouteData.DataTokens["area"] = postedInfo.Area; IHttpHandler handler = new MvcHandler(requestContext); //ensure the controllerType is set if found, meaning it is a plugin, not locally declared if (postedInfo.Area != standardArea) { //requestContext.RouteData.Values["controllerType"] = postedInfo.ControllerType; //find the other data tokens for this route and merge... things like Namespace will be included here using (RouteTable.Routes.GetReadLock()) { var surfaceRoute = RouteTable.Routes.OfType<Route>() .SingleOrDefault(x => x.Defaults != null && x.Defaults.ContainsKey("controller") && x.Defaults["controller"].ToString() == postedInfo.ControllerName && x.DataTokens.ContainsKey("area") && x.DataTokens["area"].ToString() == postedInfo.Area); if (surfaceRoute == null) throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName + " and within the area of " + postedInfo.Area); //set the 'Namespaces' token so the controller factory knows where to look to construct it if (surfaceRoute.DataTokens.ContainsKey("Namespaces")) { requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"]; } handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext); } } //store the original URL this came in on requestContext.RouteData.DataTokens["umbraco-item-url"] = requestContext.HttpContext.Request.Url.AbsolutePath; //store the original route definition requestContext.RouteData.DataTokens["umbraco-route-def"] = routeDefinition; return handler; }
public void AttributeRouting_AmbiguousActions_ThrowsAmbiguousException(Type controllerType, string path) { // Arrange var controllerTypes = new[] { controllerType }; var routes = new RouteCollection(); AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes); HttpContextBase context = GetContext(path); RouteData routeData = routes.GetRouteData(context); RequestContext requestContext = new RequestContext(context, routeData); MvcHandler handler = new MvcHandler(requestContext); handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes)); Assert.Throws<AmbiguousMatchException>(() => handler.ProcessRequest(context)); }