protected void Application_Error(object sender, EventArgs e) { Exception lastError = Server.GetLastError(); Server.ClearError(); int statusCode = 0; if (lastError.GetType() == typeof(HttpException)) { statusCode = ((HttpException)lastError).GetHttpCode(); } else { statusCode = 500; } HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("statusCode", statusCode); routeData.Values.Add("exception", lastError); IController controller = new ErrorController(); RequestContext requestContext = new RequestContext(contextWrapper, routeData); controller.Execute(requestContext); Response.End(); }
/// <summary> /// Creates a controller instance and sets its ControllerContext depending on the current Http context. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="routeData">The route data.</param> /// <param name="context">The context.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">Can't create Controller Context if no active HttpContext instance is available.</exception> public virtual Controller CreateController(RouteData routeData = null) { // create a disconnected controller instance var controller = new GenericController(); HttpContextBase context = null; // get context wrapper from HttpContext if available if (SystemManager.CurrentHttpContext != null) context = SystemManager.CurrentHttpContext; else throw new InvalidOperationException("Can not create ControllerContext if no active HttpContext instance is available."); if (routeData == null) routeData = new RouteData(); // add the controller routing if not existing if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) { routeData.Values.Add("controller", "Generic"); } controller.UpdateViewEnginesCollection(this.GetPathTransformations()); // here we create the context for the controller passing the just created controller the httpcontext and the route data that we built above controller.ControllerContext = new ControllerContext(context, routeData, controller); return controller; }
/// <summary> /// Gets the tenantId based on the domain. /// </summary> /// <param name="routeData"></param> /// <returns>The Tennant Id, which is the Account.Id associated with the domain in the route information.</returns> public static int GetTenantId(this System.Web.Routing.RouteData routeData) { DomainRoute dr = (DomainRoute)routeData.Route; ShoelaceDbContext db = new ShoelaceDbContext(); int tenantId = -1; var sub = routeData.Values["subdomain"] as string; Account acc = null; if (sub != null) { acc = db.Accounts.FirstOrDefault(x => x.Subdomain == sub); } if (null != acc) { tenantId = acc.Id; } else { acc = db.Accounts.FirstOrDefault(x => x.VanityDomain == dr.Domain); if (acc != null) { tenantId = acc.Id; } } return(tenantId); }
protected void Application_Error() { if (HttpContext.Current == null) { // errors in Application_Start will end up here return; } if (HttpContext.Current.IsCustomErrorEnabled) { return; } var exception = Server.GetLastError(); var httpException = new HttpException(null, exception); if (httpException.GetHttpCode() == 404 && WebHelper.IsStaticResource(this.Request)) { return; } //TODO: 记录Log(忽略404,403) var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("httpException", httpException); Server.ClearError(); // Call target Controller and pass the routeData. //Ref nop&nblog IController errorController = SDFEngine.Container.Resolve<ErrorController>(); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); }
public AssetRequestHandler_Tests() { var requestContext = new Mock<RequestContext>(); var routeData = new RouteData(); request = new Mock<HttpRequestBase>(); response = new Mock<HttpResponseBase>(); cache = new Mock<HttpCachePolicyBase>(); requestHeaders = new NameValueCollection(); routeData.Values.Add("path", "test/asset.js"); requestContext.SetupGet(r => r.RouteData) .Returns(routeData); requestContext.SetupGet(r => r.HttpContext.Response) .Returns(response.Object); requestContext.SetupGet(r => r.HttpContext.Request) .Returns(request.Object); requestContext.SetupGet(r => r.HttpContext.Items) .Returns(new Dictionary<string, object>()); response.SetupGet(r => r.OutputStream).Returns(() => outputStream); response.SetupGet(r => r.Cache).Returns(cache.Object); request.SetupGet(r => r.Headers).Returns(requestHeaders); var bundleContainer = new Mock<IBundleContainer>(); bundleContainer.Setup(c => c.FindBundleContainingPath<Bundle>(It.IsAny<string>())) .Returns(() => bundle); handler = new AssetRequestHandler(requestContext.Object, () => bundleContainer.Object); }
private bool TestIncomingRouteResult(RouteData routeResult, string controller, string action, object propertySet = null) { Func<object, object, bool> valCompare = (v1, v2) => { return StringComparer.InvariantCultureIgnoreCase.Compare(v1, v2) == 0; }; bool result = valCompare(routeResult.Values["controller"], controller) && valCompare(routeResult.Values["action"], action); if (propertySet != null) { PropertyInfo[] propInfo = propertySet.GetType().GetProperties(); foreach (var pi in propInfo) { if (!(routeResult.Values.ContainsKey(pi.Name) && valCompare(routeResult.Values[pi.Name], pi.GetValue(propertySet, null)))) { result = false; break; } } } return result; }
/// <summary> /// You can take this information from cache or table from database as you like /// </summary> /// <param name="slug"></param> /// <param name="data"></param> /// <returns></returns> private string GetBySlug(string slug , RouteData data) { // you can take it from cache or sql table every ID and it's value for URL if (slug == "Eng-Mohamad-Alsaid") { data.Values["SeName"] = slug; data.Values["controller"] = "Engineers"; data.Values["action"] = "EngineerDetails"; data.Values["Engineerid"] = 1; return "OK"; } else if (slug == "Syria") { data.Values["SeCountry"] = slug; data.Values["controller"] = "Engineers"; data.Values["action"] = "EngineerDetails"; data.Values["Engineerid"] = 2; return "OK"; } else if (slug == "0090538972117") { data.Values["SeMobile"] = slug; data.Values["controller"] = "Engineers"; data.Values["action"] = "EngineerDetails"; data.Values["Engineerid"] = 3; return "OK"; } else return null; }
private void ExecuteErrorPage() { ErrorInfo errorInfo = new ErrorInfo(httpStatusCode, this.exception, HttpContext.Current.Request); RouteData routeData = new RouteData(); routeData.Values.Add("controller", this.config.ErrorControllerName); routeData.Values.Add("action", this.config.ErrorActionName); routeData.Values.Add("errorInfo", errorInfo); HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current); RequestContext requestContext = new RequestContext(httpContextWrapper, routeData); IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory(); IController errorController = controllerFactory.CreateController(requestContext, this.config.ErrorControllerName); errorController.Execute(requestContext); if (httpStatusCode > 0) { HttpContext.Current.Response.StatusCode = httpStatusCode; HttpContext.Current.Response.ContentType = "text/html"; } HttpContext.Current.Response.TrySkipIisCustomErrors = true; }
protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); WebServiceException webEx = exception as WebServiceException; if (webEx != null) { log.ErrorFormat("Api Error => {0}", webEx.ErrorMessage); } var httpException = new HttpException(null, exception); log.Error("Application Error", exception); if (!HttpContext.Current.IsCustomErrorEnabled) return; var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("httpException", httpException); Server.ClearError(); var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController( new RequestContext(new HttpContextWrapper(Context), routeData), "Error"); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); }
private void RedirectToErrorPage(Exception ex) { var httpException = ex as HttpException; var routeData = new RouteData(); routeData.Values["controller"] = "Errors"; routeData.Values["action"] = "General"; routeData.Values["exception"] = httpException; //Production: Handle any specific Http errors with custom views //Response.StatusCode = 500; //if (httpException != null) //{ // Response.StatusCode = httpException.GetHttpCode(); // switch (Response.StatusCode) // { // case 403: // routeData.Values["action"] = "Http403"; // break; // case 404: // routeData.Values["action"] = "Http404"; // break; // } //} using (var scope = AutofacConfig.Container.BeginLifetimeScope()) { var uiService = scope.Resolve<IUiService>(); IController errorsController = new ErrorsController(uiService); var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData); errorsController.Execute(requestContext); } }
public void RequestWithoutSubfolder_ForDirectoryWithoutFileAndWithouEndingSlash_AppendsDefaultFileToVirtualPath() { //arrange string virtualPath = string.Empty; var routeData = new RouteData { Route = new DirectoryRoute("admin", new Mock<IDependencyResolver>().Object) }; ; routeData.Values.Add("pathinfo", "posts"); var pageBuilder = new Mock<ISubtextPageBuilder>(); var httpHandler = new Mock<IHttpHandler>(); pageBuilder.Setup(b => b.CreateInstanceFromVirtualPath(It.IsAny<string>(), It.IsAny<Type>())).Returns( httpHandler.Object).Callback<string, Type>((vpath, type) => virtualPath = vpath); IRouteHandler routeHandler = new DirectoryRouteHandler(pageBuilder.Object, new Mock<IDependencyResolver>().Object); var httpContext = new Mock<HttpContextBase>(); httpContext.FakeRequest("~/admin/posts"); var requestContext = new RequestContext(httpContext.Object, routeData); //act routeHandler.GetHttpHandler(requestContext); //assert Assert.AreEqual("~/aspx/admin/posts/Default.aspx", virtualPath); }
public ChildActionExtensionsTest() { route = new Mock<RouteBase>(); route.Setup(r => r.GetVirtualPath(It.IsAny<RequestContext>(), It.IsAny<RouteValueDictionary>())) .Returns(() => virtualPathData); virtualPathData = new VirtualPathData(route.Object, "~/VirtualPath"); routes = new RouteCollection(); routes.Add(route.Object); originalRouteData = new RouteData(); string returnValue = ""; httpContext = new Mock<HttpContextBase>(); httpContext.Setup(hc => hc.Request.ApplicationPath).Returns("~"); httpContext.Setup(hc => hc.Response.ApplyAppPathModifier(It.IsAny<string>())) .Callback<string>(s => returnValue = s) .Returns(() => returnValue); httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>())); viewContext = new ViewContext { RequestContext = new RequestContext(httpContext.Object, originalRouteData) }; viewDataContainer = new Mock<IViewDataContainer>(); htmlHelper = new Mock<HtmlHelper>(viewContext, viewDataContainer.Object, routes); }
private void ShowCustomErrorPage(Exception exception) { HttpException httpException = exception as HttpException; if (httpException == null) httpException = new HttpException(500, "Internal Server Error", exception); Response.Clear(); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); switch (httpException.GetHttpCode()) { case 404: routeData.Values.Add("action", "Http404"); break; default: routeData.Values.Add("action", "Http404"); break; } Server.ClearError(); var contentService = (IWebContent)DependencyResolver.Current.GetService(typeof(IWebContent)); var domainService = (IDomain)DependencyResolver.Current.GetService(typeof(IDomain)); var userService = (IUser)DependencyResolver.Current.GetService(typeof(IUser)); var ecommerceService = (IECommerce)DependencyResolver.Current.GetService(typeof(IECommerce)); //var stripeService = (IStripe) DependencyResolver.Current.GetService(typeof (IStripe)); IController controller = new ErrorController(domainService, contentService, ecommerceService, userService); controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); }
public void Can_Create_View() { var routeData = new RouteData(); routeData.Values.Add("controller", "home"); var result = _viewEngine.FindView(new ControllerContext() { RouteData = routeData }, "view", null, false); Assert.IsNotNull(result.View); }
private static void Log(RouteData routeData, /*[CallerMemberName]*/string methodName = "") { var controllerName = routeData.Values["Controller"]; var actionName = routeData.Values["Action"]; var message = string.Format("{0} controller: {1} action: {2}", methodName, controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); }
protected void Application_Error() { var exception = Server.GetLastError(); var httpException = exception as HttpException; Response.Clear(); Server.ClearError(); var routeData = new RouteData(); routeData.Values["controller"] = "Errors"; routeData.Values["action"] = "General"; routeData.Values["exception"] = exception; Response.StatusCode = 500; if (httpException != null) { Response.StatusCode = httpException.GetHttpCode(); switch (Response.StatusCode) { //case 403: // routeData.Values["action"] = "Http403"; // break; case 404: routeData.Values["action"] = "Http404"; break; } } // Avoid IIS7 getting in the middle Response.TrySkipIisCustomErrors = true; IController errorsController = new ErrorsController(); HttpContextWrapper wrapper = new HttpContextWrapper(Context); var rc = new RequestContext(wrapper, routeData); errorsController.Execute(rc); }
private static HtmlHelper GetFormHelper(out StringWriter writer) { Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>(); mockHttpRequest.Setup(r => r.Url).Returns(new Uri("http://www.contoso.com/some/path")); Mock<HttpResponseBase> mockHttpResponse = new Mock<HttpResponseBase>(MockBehavior.Strict); mockHttpResponse.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => AppPathModifier + r); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(c => c.Request).Returns(mockHttpRequest.Object); mockHttpContext.Setup(c => c.Response).Returns(mockHttpResponse.Object); RouteCollection rt = new RouteCollection(); rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) }); rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) }); RouteData rd = new RouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "oldaction"); Mock<ViewContext> mockViewContext = new Mock<ViewContext>(); mockViewContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object); mockViewContext.Setup(c => c.RouteData).Returns(rd); writer = new StringWriter(); mockViewContext.Setup(c => c.Writer).Returns(writer); HtmlHelper helper = new HtmlHelper( mockViewContext.Object, new Mock<IViewDataContainer>().Object, rt); return helper; }
//protected void Application_PreRequestHandlerExecute() //{ // var culture = CultureInfo.CreateSpecificCulture("en-GB"); // culture.DateTimeFormat = CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat; // Thread.CurrentThread.CurrentCulture = culture; // culture = new CultureInfo("en-GB") {DateTimeFormat = Thread.CurrentThread.CurrentCulture.DateTimeFormat}; // Thread.CurrentThread.CurrentUICulture = culture; //} protected void Application_Error(object sender, EventArgs e) { var handleError = Convert.ToBoolean(ConfigurationManager.AppSettings["RedirectToErrorPage"]); var exception = Server.GetLastError(); Utility.WriteToLog("Global.Application_Error() : " + exception, "Error"); if (!handleError) return; Server.ClearError(); var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("exception", exception); if (exception.GetType() == typeof(HttpException)) { routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode()); } else { routeData.Values.Add("statusCode", 500); } IController controller = new ErrorController(); controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); Response.End(); }
protected void Application_Error() { var exception = Server.GetLastError(); var httpException = exception as HttpException; Response.Clear(); Server.ClearError(); var routeData = new RouteData(); routeData.Values["controller"] = "Errors"; routeData.Values["action"] = "General"; routeData.Values["exception"] = exception; Response.StatusCode = 500; if (httpException != null) { Response.StatusCode = httpException.GetHttpCode(); switch (Response.StatusCode) { case 403: routeData.Values["action"] = "Http403"; break; case 404: routeData.Values["action"] = "Http404"; break; } } IController errorsController = new ErrorController(); var rc = new RequestContext(new HttpContextWrapper(Context), routeData); errorsController.Execute(rc); }
public void EngineLookupFailureThrows() { // Arrange ControllerBase controller = new Mock<ControllerBase>().Object; HttpContextBase httpContext = CreateHttpContext(); RouteData routeData = new RouteData(); routeData.Values["action"] = _viewName; ControllerContext context = new ControllerContext(httpContext, routeData, controller); Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); List<IViewEngine> viewEngines = new List<IViewEngine>(); viewEngines.Add(viewEngine.Object); Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines); PartialViewResult result = new PartialViewResultHelper { ViewEngineCollection = viewEngineCollection.Object }; viewEngineCollection .Expect(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName)) .Returns(new ViewEngineResult(new[] { "location1", "location2" })); viewEngine .Expect(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName, It.IsAny<bool>())) .Callback<ControllerContext, string>( (controllerContext, viewName) => { Assert.AreSame(httpContext, controllerContext.HttpContext); Assert.AreSame(routeData, controllerContext.RouteData); }) .Returns(new ViewEngineResult(new[] { "location1", "location2" })); // Act & Assert ExceptionHelper.ExpectInvalidOperationException( () => result.ExecuteResult(context), @"The partial view '" + _viewName + @"' was not found. The following locations were searched: location1 location2"); viewEngine.Verify(); viewEngineCollection.Verify(); }
public static ControllerContext GetErrorControllerContext(string actionName, string controllerName) { var cookie = new HttpCookieCollection(); cookie.Add(new HttpCookie("CultureInfo", "en-GB")); HttpRequestBase request = new System.Web.Fakes.ShimHttpRequestBase(new StubHttpRequestBase()) { CookiesGet = () => { return(cookie); } }; HttpResponseBase response = new System.Web.Fakes.ShimHttpResponseBase(new StubHttpResponseBase()) { CookiesGet = () => { return(cookie); } }; HttpContextBase context = new System.Web.Fakes.ShimHttpContextBase(new StubHttpContextBase()) { RequestGet = () => { return(request); }, ResponseGet = () => { return(response); } }; ControllerBase baseStub = new BaseController();// //System.Web.Mvc.Fakes.ShimControllerBase(new StubControllerBase()) //{ //}; var routeData = new System.Web.Routing.RouteData(); routeData.Values["controller"] = controllerName; routeData.Values["action"] = actionName; return(new ControllerContext(context, routeData, baseStub)); }
private static UrlHelper GetUrlHelper(RouteData routeData = null, RouteCollection routeCollection = null) { HttpContextBase httpcontext = MvcHelper.GetHttpContext("/app/", null, null); var urlHelper = new UrlHelper(new RequestContext(httpcontext, routeData ?? new RouteData()), routeCollection ?? new RouteCollection()); return urlHelper; }
static string GetNamespaceFrom(RouteData routeData) { return string.Format("{0}.{1}.{2}", routeData.Values["boundedContext"], routeData.Values["module"], routeData.Values["feature"]); }
public static Stack<MenuItem> SetSelectedPath(IEnumerable<MenuItem> menuItems, RouteData currentRouteData, string targetUrl, HttpContextBase httpContext) { if (menuItems == null) return null; foreach (var menuItem in menuItems) { var selectedPath = SetSelectedPath(menuItem.Items, currentRouteData, targetUrl, httpContext); if (selectedPath != null) { menuItem.Selected = true; selectedPath.Push(menuItem); return selectedPath; } if (!UrlUtility.RouteMatches(menuItem.RouteValues, currentRouteData.Values) && !UrlUtility.UrlMatches(menuItem.Href, targetUrl, httpContext)) { continue; } menuItem.Selected = true; selectedPath = new Stack<MenuItem>(); selectedPath.Push(menuItem); return selectedPath; } return null; }
private static RouteData GetRouteData() { var rd = new RouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "oldaction"); return rd; }
public static string RenderPartialView(string controllerName, string partialView, object model) { var context = new HttpContextWrapper(System.Web.HttpContext.Current) as HttpContextBase; var routes = new System.Web.Routing.RouteData(); routes.Values.Add("controller", controllerName); var requestContext = new RequestContext(context, routes); string requiredString = requestContext.RouteData.GetRequiredString("controller"); var controllerFactory = ControllerBuilder.Current.GetControllerFactory(); var controller = controllerFactory.CreateController(requestContext, requiredString) as ControllerBase; controller.ControllerContext = new ControllerContext(context, routes, controller); var ViewData = new ViewDataDictionary(); var TempData = new TempDataDictionary(); ViewData.Model = model; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialView); var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); return(sw.GetStringBuilder().ToString()); } }
public static HtmlHelper GetHtmlHelper(bool clientValidationEnabled = true) { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(Substitute.For<IViewEngine>()); var controller = Substitute.For<ControllerBase>(); var httpContext = Substitute.For<HttpContextBase>(); httpContext.Request.Headers.Returns(new NameValueCollection()); var routeData = new RouteData(); routeData.Values["controller"] = "home"; routeData.Values["action"] = "index"; var controllerContext = new ControllerContext(httpContext, routeData, controller); var viewContext = new ViewContext(controllerContext, Substitute.For<IView>(), new ViewDataDictionary(), new TempDataDictionary(), new StringWriter()) { HttpContext = httpContext, ClientValidationEnabled = clientValidationEnabled, UnobtrusiveJavaScriptEnabled = clientValidationEnabled, FormContext = new FormContext() }; return new HtmlHelper(viewContext, Substitute.For<IViewDataContainer>()); }
public given_controller() { this.bus = Mock.Of<ICommandBus>(); this.conferenceDao = Mock.Of<IConferenceDao>(x => x.GetConferenceAlias(conferenceAlias.Code) == conferenceAlias); this.orderDao = Mock.Of<IOrderDao>(); this.routes = new RouteCollection(); this.routeData = new RouteData(); this.routeData.Values.Add("conferenceCode", conferenceAlias.Code); var requestMock = new Mock<HttpRequestBase>(MockBehavior.Strict); requestMock.SetupGet(x => x.ApplicationPath).Returns("/"); requestMock.SetupGet(x => x.Url).Returns(new Uri("http://localhost/request", UriKind.Absolute)); requestMock.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()); var responseMock = new Mock<HttpResponseBase>(MockBehavior.Strict); responseMock.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s); var context = Mock.Of<HttpContextBase>(c => c.Request == requestMock.Object && c.Response == responseMock.Object); this.sut = new RegistrationController(this.bus, this.orderDao, this.conferenceDao); this.sut.ConferenceAlias = conferenceAlias; this.sut.ConferenceCode = conferenceAlias.Code; this.sut.ControllerContext = new ControllerContext(context, this.routeData, this.sut); this.sut.Url = new UrlHelper(new RequestContext(context, this.routeData), this.routes); }
public override RouteData GetRouteData( HttpContextBase httpContext ) { RouteData res = null; string virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring( 2 ) + httpContext.Request.PathInfo; Match m = _regex.Match( virtualPath ); if( m.Success ) { var path = m.Groups[ "path" ].Value.Split( '/' ); var seoPartsCatalogItems = SeoPartsCatalogDac.GetCatalogItemsByVirtualPath( path.Skip( 1 ).ToArray() ); if( seoPartsCatalogItems != null ) { res = new RouteData( this, _routeHandler ); res.DataTokens.Add( "SeoPartsCatalogItems", seoPartsCatalogItems ); res.Values.Add( "ID", seoPartsCatalogItems.Last().ID ); } else { throw new HttpException( (int)HttpStatusCode.NotFound, "Not Found" ); } } return res; }
public void Test_Dynamic_Module_Filter() { // Arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.HttpMethod).Returns("GET"); request.SetupGet(r => r.Url).Returns(new Uri("http://localhost/uac/dyn/0/The-test=module-0")); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(request.Object); var routeData = new RouteData(); // routeData.Values.Add("moduleid", "0"); var fakeRepo = new FakeModuleRepository(); var fakeMembership = new FakeModuleMembership(); var controller = new DynamicModuleController(fakeRepo, fakeMembership); var filterContext = new Mock<ActionExecutingContext>(); filterContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object); filterContext.SetupGet(c => c.RouteData).Returns(routeData); filterContext.SetupGet(c => c.ActionParameters).Returns(new Dictionary<string, object>()); filterContext.Setup(c => c.Controller).Returns(controller); var attrib = new DynamicModuleActionAttribute(); // Act attrib.OnActionExecuting(filterContext.Object); // Assert Assert.IsNotNull(filterContext.Object.ActionParameters["module"]); Assert.IsInstanceOfType(filterContext.Object.ActionParameters["module"], typeof(Module)); }
private void Log(string methodName, RouteData routeData) { var controllerName = routeData.Values["controller"]; var actionName = routeData.Values["action"]; var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); }
public void Test_Dynamic_Module_Filter_Admin_User() { // Arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.HttpMethod).Returns("GET"); request.SetupGet(r => r.Url).Returns(new Uri("http://localhost/uac/dyn/0/The-test-module-0")); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(request.Object); var routeData = new RouteData(); // routeData.Values.Add("moduleid", "0"); var fakeRepo = new FakeModuleRepository(); var fakeMembership = new FakeModuleMembership("Fake Admin", "*****@*****.**"); FakeModuleMembership.FakeUserId = Guid.NewGuid(); // change the user id for one that is not authorized var controller = new DynamicModuleController(fakeRepo, fakeMembership); var filterContext = new Mock<ActionExecutingContext>(); filterContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object); filterContext.SetupGet(c => c.RouteData).Returns(routeData); filterContext.SetupGet(c => c.ActionParameters).Returns(new Dictionary<string, object>()); filterContext.Setup(c => c.Controller).Returns(controller); var attrib = new DynamicModuleActionAttribute() { CheckLogin = true }; // Act attrib.OnActionExecuting(filterContext.Object); // Assert Assert.IsNotNull(filterContext.Object.ActionParameters["module"]); Assert.IsInstanceOfType(filterContext.Object.ActionParameters["module"], typeof(Module)); }
public static string RenderViewToString(string controllerName, string viewName, object viewData, List<KeyValuePair<string, object>> additionalData) { var context = HttpContext.Current; var contextBase = new HttpContextWrapper(context); var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController()); var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false); ViewDataDictionary vdd = new ViewDataDictionary(viewData); if (additionalData != null && additionalData.Any()) additionalData.ForEach(vdd.Add); var writer = new StringWriter(); var viewContext = new ViewContext(controllerContext, razorViewResult.View, vdd, new TempDataDictionary(), writer); razorViewResult.View.Render(viewContext, writer); return writer.ToString(); }
private void EnsureDataToken(string key, System.Web.Routing.RouteData routeData) { if (!routeData.DataTokens.ContainsKey(key) && routeData.Values.ContainsKey(key)) { int id = Convert.ToInt32(routeData.Values[key]); routeData.DataTokens[key] = engine.Persister.Get(id); } }
private void EnsureDataToken(string key, System.Web.Routing.RouteData routeData) { if (!routeData.DataTokens.ContainsKey(key) && routeData.Values.ContainsKey(key)) { object value = routeData.Values[key]; var item = value as ContentItem; if (item == null) { int id = Convert.ToInt32(routeData.Values[key]); item = engine.Persister.Get(id); } routeData.DataTokens[key] = item; } }
} // End of the UnprotectCookieValue method /// <summary> /// Get a 404 not found page /// </summary> /// <returns>A string with html</returns> public static string GetHttpNotFoundPage() { // Create the string to return string htmlString = ""; // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); // Get the error page StaticPage staticPage = StaticPage.GetOneByConnectionId(4, currentDomain.front_end_language); staticPage = staticPage != null ? staticPage : new StaticPage(); // Get the translated texts KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC"); // Create the Route data System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData(); routeData.Values.Add("controller", "home"); // Create the controller context System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Blogsite.Controllers.homeController()); // Create the bread crumb list List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2); breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/")); breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404")); // Set form values context.Controller.ViewBag.BreadCrumbs = breadCrumbs; context.Controller.ViewBag.CurrentCategory = new Category(); context.Controller.ViewBag.TranslatedTexts = tt; context.Controller.ViewBag.CurrentDomain = currentDomain; context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language); context.Controller.ViewBag.StaticPage = staticPage; // Render the view using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture)) { string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml"; System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null); razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter); htmlString += stringWriter.ToString(); } // Return the string return htmlString; } // End of the GetHttpNotFoundPage method
protected virtual string GetAreaName(System.Web.Routing.RouteData routeData) { if (routeData.Values.ContainsKey("pluginName")) { var pluginName = routeData.GetRequiredString("pluginName"); return(pluginName); } object obj2; if (routeData.DataTokens.TryGetValue("area", out obj2)) { return(obj2 as string); } return(GetAreaName(routeData.Route)); }
private bool _IsAuthrized(System.Web.HttpContextBase httpContextBase, string url) { System.Security.Principal.IPrincipal user = httpContextBase.User; bool result; try { HttpWorkerRequest request = new Authorization.SimpleHttpWorkerRequest(url); HttpContext httpContext = new HttpContext(request); System.Web.HttpContextWrapper httpContextWrapper = new System.Web.HttpContextWrapper(httpContext); System.Web.Routing.RouteData routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(httpContextWrapper); httpContext.User = user; System.Web.HttpContextBase _httpContextBase = new System.Web.HttpContextWrapper(httpContext); System.Web.Routing.RequestContext requestContext = new System.Web.Routing.RequestContext(_httpContextBase, routeData); string controllerName = requestContext.RouteData.GetRequiredString("controller"); string actionName = requestContext.RouteData.GetRequiredString("action"); IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory(); try { IController controller = factory.CreateController(requestContext, controllerName); if (controller is ControllerBase) { ControllerContext controllerContext = new ControllerContext(requestContext, controller as ControllerBase); result = this.invoker.IsAuthrized(controllerContext, actionName); } else { result = true; } } catch (System.Exception) { result = false; } } catch { result = false; } return(result); }
public void ProcessRequest(HttpContext context) { System.Web.Routing.RouteData routeData = this.RequestContext.RouteData; }
/// <summary> /// Set up error handling to log exceptions and defer to error controller or as last resort static HTML error page. /// </summary> public override void Application_Error(object sender, EventArgs e) { if (!HttpContext.Current.IsCustomErrorEnabled) { return; } try { var ex = HttpContext.Current.Server.GetLastError(); var httpException = ex as HttpException; var logger = DependencyResolver.Current.GetService <ILogger>(); logger.LogException(ex, string.Format("Caught unhandled exception in Store.\r\n {0}", ex.Message + "\r\n" + ex.StackTrace)); var routeData = new System.Web.Routing.RouteData(); routeData.Values.Add("controller", "Error"); if (httpException != null) { switch (httpException.GetHttpCode()) { case 401: routeData.Values.Add("action", "Forbidden"); break; case 404: routeData.Values.Add("action", "NotFound"); break; default: routeData.Values.Add("action", "InternalServerError"); break; } } else { routeData.Values.Add("action", "InternalServerError"); } if (ex != null && ex is HttpAntiForgeryException) { var auditLogger = DependencyResolver.Current.GetService <IAuditLogger>(); var url = HttpContext.Current.Request.Url.OriginalString; var details = new Dictionary <string, object>(); details.Add("url", url); details.Add("ip", HttpContext.Current.Request.UserHostAddress); details.Add("referrer", HttpContext.Current.Request.UrlReferrer); details.Add("user agent", HttpContext.Current.Request.UserAgent); if (HttpContext.Current.Request.Form != null && HttpContext.Current.Request.Form.Count > 0) { var formData = new Dictionary <string, string>(); foreach (var key in HttpContext.Current.Request.Form.AllKeys) { formData.Add(key, HttpContext.Current.Request.Form[key].ToString()); } details.Add("form data", formData); } auditLogger.Log( AuditActionTypes.SecurityCsrf, $"CSRF attempt prevented on url: {url}", string.Empty, string.Empty, string.Empty, details); } routeData.Values.Add("error", ex); HttpContext.Current.Server.ClearError(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.TrySkipIisCustomErrors = true; IController errorController = new ErrorController(); errorController.Execute(new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData)); } catch { // This is a last ditch effort in case something goes wrong with the regular error handling. HttpContext.Current.Response.Clear(); HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.InternalServerError; HttpContext.Current.Response.ContentType = "text/html"; HttpContext.Current.Response.WriteFile("~/Content/Error.html"); } }
public static string SortableColumn(this HtmlHelper htmlHelper, string linkText, string columnName, object routeValues) { //automatically determine the current action System.Web.Routing.RouteData data = htmlHelper.ViewContext.Controller.ControllerContext.RouteData; string actionName = data.GetRequiredString("action"); StringBuilder sb = new StringBuilder(); var vals = new RouteValueDictionary(routeValues); string sidx = String.Empty; if (System.Web.HttpContext.Current.Request["sidx"] != null) { sidx = System.Web.HttpContext.Current.Request["sidx"].ToString(); } //modify the sidx if (vals.ContainsKey("sidx") == false) { vals.Add("sidx", columnName); } else { vals["sidx"] = columnName; } //get the sort order from the request variable if it exists string sord = String.Empty; if (System.Web.HttpContext.Current.Request["sord"] != null) { sord = System.Web.HttpContext.Current.Request["sord"].ToString(); } //add the sord key if needed if (vals.ContainsKey("sord") == false) { vals.Add("sord", String.Empty); } //if column matches if (sidx.Equals(columnName, StringComparison.CurrentCultureIgnoreCase) == true) { if (sord.Equals("asc", StringComparison.CurrentCultureIgnoreCase) == true) { //draw the ascending sort indicator using the wingdings font. sb.Append(" <font face='Wingdings 3'>p</font>"); vals["sord"] = "desc"; } else { sb.Append(" <font face='Wingdings 3'>q</font>"); vals["sord"] = "asc"; } } else { //if the column does not match then force the next sort to ascending order vals["sord"] = "asc"; } //Use the ActionLink to build the link and insert it into the string sb.Insert(0, System.Web.Mvc.Html.LinkExtensions.ActionLink(htmlHelper, linkText, actionName, vals)); return(sb.ToString()); }
public SessionControllerHandler(System.Web.Routing.RouteData routeData) : base(routeData) { }
protected void JumpMobileUrl(System.Web.Routing.RouteData route, string url = "") { string pathAndQuery = base.Request.Url.PathAndQuery; string wX = pathAndQuery; if (route == null) { return; } string lower = route.Values["controller"].ToString().ToLower(); string str = route.Values["action"].ToString().ToLower(); string str1 = (route.DataTokens["area"] == null ? "" : route.DataTokens["area"].ToString().ToLower()); if (str1 == "mobile") { return; } if (str1 == "web") { IsAutoJumpMobile = true; } if (IsAutoJumpMobile && IsMobileTerminal && Regex.Match(pathAndQuery, "\\/m(\\-.*)?").Length < 1) { JumpUrlRoute routeUrl = GetRouteUrl(lower, str, str1, pathAndQuery); switch (visitorTerminalInfo.Terminal) { case EnumVisitorTerminal.WeiXin: { if (routeUrl != null) { wX = routeUrl.WX; } wX = string.Concat("/m-weixin", wX); break; } case EnumVisitorTerminal.IOS: { if (routeUrl != null) { wX = routeUrl.WAP; } wX = string.Concat("/m-ios", wX); break; } default: { if (routeUrl != null) { wX = routeUrl.WAP; } wX = string.Concat("/m-wap", wX); break; } } if (routeUrl.IsSpecial) { if (routeUrl.PC.ToLower() == "/shop") { string str2 = route.Values["id"].ToString(); long num = 0; long id = 0; if (!long.TryParse(str2, out num)) { num = 0; } if (num > 0) { VShopInfo vShopByShopId = ServiceHelper.Create <IVShopService>().GetVShopByShopId(num); if (vShopByShopId != null) { id = vShopByShopId.Id; } } wX = string.Concat(wX, "/", id.ToString()); } if (routeUrl.PC.ToLower() == "/order/submit") { string empty = string.Empty; object item = route.Values["cartitemids"]; empty = (item != null ? item.ToString() : base.Request.QueryString["cartitemids"]); wX = string.Concat(wX, "/?cartItemIds=", empty); } } if (!string.IsNullOrWhiteSpace(url)) { wX = url; } if (!IsExistPage(string.Concat(base.Request.Url.Scheme, "://", base.Request.Url.Authority, wX))) { wX = (visitorTerminalInfo.Terminal != EnumVisitorTerminal.WeiXin ? "/m-wap/" : "/m-weixin/"); } base.Response.Redirect(wX); } }
/// <summary> /// Get the data address of an item from type and route /// </summary> /// <param name="type">the type of the item</param> /// <param name="rd">the route data from which to get the data address</param> /// <returns>the data address</returns> public abstract Address GetAddress(Type type, System.Web.Routing.RouteData rd);
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext, SmartAuthorizeAttribute.AuthorizeResult result) { bool isAjaxRequest = filterContext.HttpContext.Request.IsAjaxRequest(); if (isAjaxRequest) { filterContext.Result = new InsufficientAuthorizationsResult(); } else { System.Web.Routing.RouteData routeData = filterContext.RouteData; string virtualPath = routeData.Route.GetVirtualPath(filterContext.RequestContext, routeData.Values).VirtualPath; if (result == SmartAuthorizeAttribute.AuthorizeResult.SessionOut) { System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(new { controller = "Error", action = "SessionOut", area = "", returnUrl = virtualPath }); filterContext.Result = new RedirectToRouteResult(dict); } else { if (result == SmartAuthorizeAttribute.AuthorizeResult.NotInRoles) { filterContext.Controller.TempData["Error_InsufficientAuthorization_Roles"] = this._rolesSplit; System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(new { controller = "Error", action = "InsufficientAuthorization", area = "" }); filterContext.Result = new RedirectToRouteResult(dict); } else { if (result == SmartAuthorizeAttribute.AuthorizeResult.NotInUsers) { filterContext.Controller.TempData["Error_InsufficientAuthorization_Users"] = this._usersSplit; System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(new { controller = "Error", action = "InsufficientAuthorization", area = "" }); filterContext.Result = new RedirectToRouteResult(dict); } else { System.Web.Routing.RouteValueDictionary dict = new System.Web.Routing.RouteValueDictionary(new { controller = "Account", action = "Login", area = "", returnUrl = virtualPath }); filterContext.Result = new RedirectToRouteResult(dict); } } } } }
public void ProcessRequest(HttpContext context) { HttpContext.Current.Items.Add("ProcessStartTime", (DateTime.Now - new DateTime(1970, 1, 1)).TotalMilliseconds); System.Threading.Thread.CurrentThread.Name = requestID; System.Web.Routing.RouteData routeData = context.Request.RequestContext.RouteData; actionName = routeData.Values["ResourceName"].ToString(); HttpContext.Current.Items.Add("ActionName", actionName); if (actionName == null) { helperObj.FlushErrorResponse(400, statusDescription: "Bad Request ( No Action Specified )"); } else { if (!actionName.Contains(".")) { helperObj.Format = ApiHelper.JsonFormat; } else { if (actionName.Split('.').Last().ToUpper() != ApiHelper.XmlFormat && actionName.Split('.').Last().ToUpper() != ApiHelper.JsonFormat) { helperObj.FlushErrorResponse(404); } } if (actionName.Split('.').Last().ToUpper() == ApiHelper.XmlFormat) { helperObj.Format = ApiHelper.XmlFormat; } else { helperObj.Format = ApiHelper.JsonFormat; } actionName = actionName.Split('.').First(); if (helperObj.IsXmlFormat) { helperObj.InitializeXmlDoc(); } else { helperObj.InitializeJSonObjects(); } } if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() == "182.74.61.105" || HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() == "182.74.61.106" || HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() == "183.82.2.22") { helperObj.SaveRequest(actionName); } userObj = (Dictionary <string, object>)HttpContext.Current.Items["UserObject"]; if (userObj != null && userObj.ContainsKey("UserID")) { userId = Convert.ToInt32(userObj["UserID"]); } if (userObj != null && userObj.ContainsKey("CountryID")) { countryID = Convert.ToInt32(userObj["CountryID"]); } if (userId == 5 || userId == 1 || userId == 2) { } else { short siteIsUnderMaintanance = 0; siteIsUnderMaintanance = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["siteIsUnderMaintanance"].ToString()); if (siteIsUnderMaintanance == 1) { JObject responseObj = new JObject(); responseObj = new JObject(new JProperty("Success", false), new JProperty("Message", "Please wait App is Under Maintenance")); context.Response.Write(responseObj); context.Response.End(); } } switch (actionName) { case ApiHelper.REGISTER: Registration(context); break; case ApiHelper.VALIDATE_OTP: ValidateOTP(context); break; case ApiHelper.CREATE_GROUPCALL: CreateGroupCall(context); break; case ApiHelper.EDIT_GROUPCALL: EditGroupCall(context); break; case ApiHelper.ADD_PARTICIPANT_IN_CONFERENCE: AddParticipantInGroupCall(context); break; case ApiHelper.GET_ALL_GROUP_CALLS: GetAllGroupCalls(context); break; case ApiHelper.GET_REPORTS_BY_BATCH_ID: GetReportsByBatchIdNew(context); break; case ApiHelper.UPDATE_GROUPCALL_NAME: UpdateGroupCallName(context); break; case ApiHelper.PROFILE_IMAGE: ProfileImage(context); break; case ApiHelper.DELETE_GROUPCALL: DeleteGroupCall(context); break; case ApiHelper.MUTEUNMUTE: MuteUnMute(context); break; case ApiHelper.HANGUP: Hangup(context); break; case ApiHelper.ANDROID_INAPP_PURCHASE: AndroidBuyCredits(context); break; case ApiHelper.GET_COUNTRIES: GetCountries(context); break; case ApiHelper.DIAL: Dial(context); break; case ApiHelper.GET_GROUPCALL_ROOM: GetGroupCallRoom(context); break; case ApiHelper.GRPCALL_CANCEL: GrpCallCancel(context); break; case ApiHelper.CHECK_USER_CONFIRMATION: CheckUserConfirmation(context); break; case ApiHelper.USER_BALANCE: UserBalance(context); break; case ApiHelper.UPDATE_PROFILE: UpdateProfile(context); break; case ApiHelper.INAPP_PURCAHSE: IOSBuyCredits(context); break; case ApiHelper.LEAVE_GROUP_CALL: LeaveGroupCall(context); break; case ApiHelper.OTP_CALL: OtpCall(context); break; case ApiHelper.INAPP_PURCHASE_HISTORY: InAppPurchaseHistory(context); break; case "IOSPUSH": IOSPUSH(); break; } }
public static void AliasRouteEx(this RouteCollection routes, string[] aliases, RouteData routeData) { foreach (var alias in aliases) { routes.AliasRouteEx(alias, routeData, null, (left, right) => left); } }
public string BuildUrl(Route route, RequestContext requestContext, RouteValueDictionary userValues, RouteValueDictionary constraints, out RouteValueDictionary usedValues) { usedValues = null; if (requestContext == null) { return(null); } RouteData routeData = requestContext.RouteData; RouteValueDictionary defaultValues = route != null ? route.Defaults : null; RouteValueDictionary ambientValues = routeData.Values; if (defaultValues != null && defaultValues.Count == 0) { defaultValues = null; } if (ambientValues != null && ambientValues.Count == 0) { ambientValues = null; } if (userValues != null && userValues.Count == 0) { userValues = null; } // Check URL parameters // It is allowed to take ambient values for required parameters if: // // - there are no default values provided // - the default values dictionary contains at least one required // parameter value // bool canTakeFromAmbient; if (defaultValues == null) { canTakeFromAmbient = true; } else { canTakeFromAmbient = false; foreach (KeyValuePair <string, bool> de in parameterNames) { if (defaultValues.ContainsKey(de.Key)) { canTakeFromAmbient = true; break; } } } bool allMustBeInUserValues = false; foreach (KeyValuePair <string, bool> de in parameterNames) { string parameterName = de.Key; // Is the parameter required? if (defaultValues == null || !defaultValues.ContainsKey(parameterName)) { // Yes, it is required (no value in defaults) // Has the user provided value for it? if (userValues == null || !userValues.ContainsKey(parameterName)) { if (allMustBeInUserValues) { return(null); // partial override => no match } if (!canTakeFromAmbient || ambientValues == null || !ambientValues.ContainsKey(parameterName)) { return(null); // no value provided => no match } } else if (canTakeFromAmbient) { allMustBeInUserValues = true; } } } // Check for non-url parameters if (defaultValues != null) { foreach (var de in defaultValues) { string parameterName = de.Key; if (parameterNames.ContainsKey(parameterName)) { continue; } object parameterValue = null; // Has the user specified value for this parameter and, if // yes, is it the same as the one in defaults? if (userValues != null && userValues.TryGetValue(parameterName, out parameterValue)) { object defaultValue = de.Value; if (defaultValue is string && parameterValue is string) { if (String.Compare((string)defaultValue, (string)parameterValue, StringComparison.Ordinal) != 0) { return(null); // different value => no match } } else if (defaultValue != parameterValue) { return(null); // different value => no match } } } } // We're a match, generate the URL var ret = new StringBuilder(); usedValues = new RouteValueDictionary(); bool canTrim = true; // Going in reverse order, so that we can trim without much ado int tokensCount = tokens.Length - 1; for (int i = tokensCount; i >= 0; i--) { PatternToken token = tokens [i]; if (token == null) { if (i < tokensCount && ret.Length > 0 && ret [0] != '/') { ret.Insert(0, '/'); } continue; } if (token.Type == PatternTokenType.Literal) { ret.Insert(0, token.Name); continue; } string parameterName = token.Name; object tokenValue; #if SYSTEMCORE_DEP if (userValues.GetValue(parameterName, out tokenValue)) { if (tokenValue != null) { usedValues.Add(parameterName, tokenValue.ToString()); } if (!defaultValues.Has(parameterName, tokenValue)) { canTrim = false; if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } continue; } if (defaultValues.GetValue(parameterName, out tokenValue)) { object ambientTokenValue; if (ambientValues.GetValue(parameterName, out ambientTokenValue)) { tokenValue = ambientTokenValue; } if (!canTrim && tokenValue != null) { ret.Insert(0, tokenValue.ToString()); } usedValues.Add(parameterName, tokenValue.ToString()); continue; } canTrim = false; if (ambientValues.GetValue(parameterName, out tokenValue)) { if (tokenValue != null) { ret.Insert(0, tokenValue.ToString()); usedValues.Add(parameterName, tokenValue.ToString()); } continue; } #endif } // All the values specified in userValues that aren't part of the original // URL, the constraints or defaults collections are treated as overflow // values - they are appended as query parameters to the URL if (userValues != null) { bool first = true; foreach (var de in userValues) { string parameterName = de.Key; #if SYSTEMCORE_DEP if (parameterNames.ContainsKey(parameterName) || defaultValues.Has(parameterName) || constraints.Has(parameterName)) { continue; } #endif object parameterValue = de.Value; if (parameterValue == null) { continue; } var parameterValueAsString = parameterValue as string; if (parameterValueAsString != null && parameterValueAsString.Length == 0) { continue; } if (first) { ret.Append('?'); first = false; } else { ret.Append('&'); } ret.Append(Uri.EscapeDataString(parameterName)); ret.Append('='); if (parameterValue != null) { ret.Append(Uri.EscapeDataString(de.Value.ToString())); } usedValues.Add(parameterName, de.Value.ToString()); } } return(ret.ToString()); }
private bool ProcessConstraintInternal(HttpContextBase httpContext, Route route, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection, RequestContext reqContext, out bool invalidConstraint) { invalidConstraint = false; IRouteConstraint irc = constraint as IRouteConstraint; if (irc != null) { return(irc.Match(httpContext, route, parameterName, values, routeDirection)); } string s = constraint as string; if (s != null) { string v = null; object o; // NOTE: If constraint was not an IRouteConstraint, is is asumed // to be an object 'convertible' to string, or at least this is how // ASP.NET seems to work by the tests i've done latelly. (pruiz) if (values != null && values.TryGetValue(parameterName, out o)) { v = Convert.ToString(o, CultureInfo.InvariantCulture); } if (!String.IsNullOrEmpty(v)) { return(MatchConstraintRegex(v, s)); } else if (reqContext != null) { RouteData rd = reqContext != null ? reqContext.RouteData : null; RouteValueDictionary rdValues = rd != null ? rd.Values : null; if (rdValues == null || rdValues.Count == 0) { return(false); } if (!rdValues.TryGetValue(parameterName, out o)) { return(false); } v = Convert.ToString(o, CultureInfo.InvariantCulture); if (String.IsNullOrEmpty(v)) { return(false); } return(MatchConstraintRegex(v, s)); } return(false); } invalidConstraint = true; return(false); }
public static void AliasRouteEx(this RouteCollection routes, string alias, RouteData routeData, object aliasConstraints) { routes.AliasRouteEx(alias, routeData, null, (left, right) => left); }