当前位置: 首页>>代码示例>>C#>>正文


C# PublishedContentRequest.TrySetTemplate方法代码示例

本文整理汇总了C#中Umbraco.Web.Routing.PublishedContentRequest.TrySetTemplate方法的典型用法代码示例。如果您正苦于以下问题:C# PublishedContentRequest.TrySetTemplate方法的具体用法?C# PublishedContentRequest.TrySetTemplate怎么用?C# PublishedContentRequest.TrySetTemplate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Umbraco.Web.Routing.PublishedContentRequest的用法示例。


在下文中一共展示了PublishedContentRequest.TrySetTemplate方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TryFindContent

        public override bool TryFindContent(PublishedContentRequest contentRequest)
        {
            // eg / or /path/to/whatever
            var url = contentRequest.Uri.GetAbsolutePathDecoded();

            var mdRoot = "/" + MarkdownLogic.BaseUrl;
            if (url.StartsWith("/projects/umbraco-pro/contour/documentation"))
                mdRoot = "/projects";

            // ensure it's a md url
            if (url.StartsWith(mdRoot) == false)
                return false; // not for us

            // find the root content
            var node = FindContent(contentRequest, mdRoot);
            if (node == null)
                return false;

            // kill those old urls
            foreach (var s in new []{ "master", "v480" })
                if (url.StartsWith(mdRoot + "/" + s))
                {
                    url = url.Replace(mdRoot + "/" + s, mdRoot);
                    contentRequest.SetRedirectPermanent(url);
                    return true;
                }

            // find the md file
            var mdFilepath = FindMarkdownFile(url);
            if (mdFilepath == null)
            {
                // clear the published content (that was set by FindContent) to cause a 404, and in
                // both case return 'true' because there's no point other finders try to handle the request
                contentRequest.PublishedContent = null;
                return true;
            }

            // set the context vars
            var httpContext = contentRequest.RoutingContext.UmbracoContext.HttpContext;
            httpContext.Items[MarkdownLogic.MarkdownPathKey] = mdFilepath;
            httpContext.Items["topicTitle"] = string.Join(" - ", httpContext.Request.RawUrl
                .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
                .Skip(1)
                .Reverse());

            // override the template
            const string altTemplate = "DocumentationSubpage";
            var templateIsSet = contentRequest.TrySetTemplate(altTemplate);
            //httpContext.Trace.Write("Markdown Files Handler",
            //    string.Format("Template changed to: '{0}' is {1}", altTemplate, templateIsSet));

            // be happy
            return true;
        }
开发者ID:KerwinMa,项目名称:OurUmbraco,代码行数:54,代码来源:DocumentationContentFinder.cs

示例2: GetUmbracoRouteValues_Find_Custom_Controller

        public void GetUmbracoRouteValues_Find_Custom_Controller()
        {
            var router = new UmbracoRouter(Mock.Of<IRouter>());
            var httpCtxAccessor = new Mock<IHttpContextAccessor>();
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(context => context.Request).Returns(Mock.Of<HttpRequest>());
            httpCtxAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext.Object);
            var umbCtx = new UmbracoContext(httpCtxAccessor.Object);
            var urlProvider = new UrlProvider(umbCtx, Enumerable.Empty<IUrlProvider>());
            var routingCtx = new RoutingContext(Enumerable.Empty<IContentFinder>(), Mock.Of<ILastChanceContentFinder>(), urlProvider);
            var templateService = new Mock<ITemplateService>();
            templateService.Setup(service => service.GetTemplate("Hello")).Returns(Mock.Of<ITemplate>(template => template.Alias == "Hello"));
            var pcr = new PublishedContentRequest(routingCtx, templateService.Object, Mock.Of<ILoggerFactory>(), httpCtxAccessor.Object)
            {
                PublishedContent = new PublishedContent()
                {
                    ContentType = "Custom"
                }
            };
            pcr.TrySetTemplate("Hello");
            umbCtx.Initialize(pcr);
            var actionDescriptors = new Mock<IActionDescriptorsCollectionProvider>();
            actionDescriptors.Setup(provider => provider.ActionDescriptors).Returns(new ActionDescriptorsCollection(
                new List<ActionDescriptor>()
                {
                    new ControllerActionDescriptor()
                    {
                        Name = "Hello",
                        ControllerName = "Custom",
                        ControllerTypeInfo = typeof(UmbracoController).GetTypeInfo()
                    }
                }, 0));

            var result = router.GetUmbracoRouteValues(umbCtx, new UmbracoControllerTypeCollection(actionDescriptors.Object));

            Assert.Equal("Custom", result.ControllerName);
            Assert.Equal("Hello", result.ActionName);
        }
开发者ID:vnbaaij,项目名称:Umbraco9,代码行数:38,代码来源:UmbracoRouterTests.cs

示例3: TryFindContent

		public bool TryFindContent(PublishedContentRequest contentRequest)
		{
			var stores = StoreHelper.GetAllStores();

			if (!stores.Any())
			{
				return false;
			}

			var uwebshopRequest = UwebshopRequest.Current;
			var content = uwebshopRequest.Product ?? uwebshopRequest.Category ?? uwebshopRequest.PaymentProvider ?? // in case ResolveUwebshopEntityUrl was already called from the module
						  IO.Container.Resolve<IUrlRewritingService>().ResolveUwebshopEntityUrl().Entity;

			if (content is PaymentProvider)
			{
				var paymentProvider = content as PaymentProvider;

				Log.Instance.LogDebug("UmbracoDefaultAfterRequestInit paymentProvider: " + paymentProvider.Name);

				new PaymentRequestHandler().HandleuWebshopPaymentRequest(paymentProvider);

				var publishedContent = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(paymentProvider.Id);
				if (publishedContent == null) return false;
				contentRequest.PublishedContent = publishedContent;

				SetRequestCulture(contentRequest);
				return true;
			}

			if (content is Category)
			{
				var categoryFromUrl = content as Category;

				if (categoryFromUrl.Disabled) return false;

				if (Access.HasAccess(categoryFromUrl.Id, categoryFromUrl.Path, Membership.GetUser()))
				{
					var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id);
					if (doc != null)
					{
						contentRequest.PublishedContent = doc;
						var altTemplate = HttpContext.Current.Request["altTemplate"];
						contentRequest.TrySetTemplate(altTemplate);

						SetRequestCulture(contentRequest);
						return true;
					}
				}
				else
				{
					if (HttpContext.Current.User.Identity.IsAuthenticated)
					{
						contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(categoryFromUrl.Path)));
					}
					contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(categoryFromUrl.Path)));
					return true;
				}
			}

			else if (content is Product)
			{
				var productFromUrl = content as Product;
				if (productFromUrl.Disabled) return false;

				if (Access.HasAccess(productFromUrl.Id, productFromUrl.Path, Membership.GetUser()))
				{
					var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id);
					if (doc != null)
					{
						contentRequest.PublishedContent = doc;
						var altTemplate = HttpContext.Current.Request["altTemplate"];
						contentRequest.TrySetTemplate(altTemplate);

						SetRequestCulture(contentRequest);
						return true;
					}
				}
				else
				{
					if (HttpContext.Current.User.Identity.IsAuthenticated)
					{
						contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(productFromUrl.Path)));
					}
					contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(productFromUrl.Path)));
					return true;
				}
			}
			return false;
		}
开发者ID:Chuhukon,项目名称:uWebshop-Releases,代码行数:89,代码来源:CatalogContentFinder.cs

示例4: TryFindContent

        public bool TryFindContent(PublishedContentRequest contentRequest)
        {
            try
            {
                if (contentRequest != null)
                {
                    //Get the current url.
                    var url = contentRequest.Uri.AbsoluteUri;

                    //Get the news nodes that are already cached.
                    var cachedNewsNodes = (Dictionary<string, ContentFinderItem>)HttpContext.Current.Cache["CachedNewsNodes"];
                    if (cachedNewsNodes != null)
                    {
                        //Check if the current url already has a news item.
                        if (cachedNewsNodes.ContainsKey(url))
                        {
                            //If the current url already has a node use that so the rest of the code doesn't need to run again.
                            var contentFinderItem = cachedNewsNodes[url];
                            contentRequest.PublishedContent = contentFinderItem.Content;
                            contentRequest.TrySetTemplate(contentFinderItem.Template);
                            return true;
                        }
                    }

                    //Split the url segments.
                    var path = contentRequest.Uri.GetAbsolutePathDecoded();
                    var parts = path.Split(new[] { '/' }, System.StringSplitOptions.RemoveEmptyEntries);

                    //The news items should contain 3 segments.
                    if (parts.Length == 3)
                    {
                        //Get all the root nodes.
                        var rootNodes = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot();

                        //Find the news item that matches the last segment in the url.
                        var newsItem = rootNodes.DescendantsOrSelf("Newsitem").Where(x => x.UrlName == parts.Last()).FirstOrDefault();
                        if(newsItem != null)
                        {
                            //Get the news item template.
                            var template = Services.FileService.GetTemplate(newsItem.TemplateId);

                            if (template != null)
                            {
                                //Store the fields in the ContentFinderItem-object.
                                var contentFinderItem = new ContentFinderItem()
                                {
                                    Template = template.Alias,
                                    Content = newsItem
                                };

                                //If the correct node is found display that node.
                                contentRequest.PublishedContent = contentFinderItem.Content;
                                contentRequest.TrySetTemplate(contentFinderItem.Template);

                                if (cachedNewsNodes != null)
                                {
                                    //Add the new ContentFinderItem-object to the cache.
                                    cachedNewsNodes.Add(url, contentFinderItem);
                                }
                                else
                                {
                                    //Create a new dictionary and store it in the cache.
                                    cachedNewsNodes = new Dictionary<string, ContentFinderItem>()
                                    {
                                        {
                                            url, contentFinderItem
                                        }
                                    };
                                    HttpContext.Current.Cache.Add("CachedNewsNodes",
                                          cachedNewsNodes,
                                          null,
                                          DateTime.Now.AddDays(1),
                                          System.Web.Caching.Cache.NoSlidingExpiration,
                                          System.Web.Caching.CacheItemPriority.High,
                                          null);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Umbraco.LogException<NewsContentFinder>(ex);
            }

            return contentRequest.PublishedContent != null;
        }
开发者ID:ksolberg,项目名称:Hybrid-Framework-for-Umbraco-v7-Best-Practises,代码行数:88,代码来源:NewsContentFinder.cs


注:本文中的Umbraco.Web.Routing.PublishedContentRequest.TrySetTemplate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。