Last active
December 8, 2017 12:45
-
-
Save carlwoodhouse/05b2a62c53625b483fce94e85de934b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Orchard.Alias; | |
using Orchard.ContentManagement; | |
namespace SomeNamespace.Alias { | |
public class AliasContentAccessor : IAliasContentAccessor { | |
ConcurrentDictionary<string, int?> _lookups; | |
private readonly IContentManager _contentManager; | |
private readonly IAliasService _aliasService; | |
public AliasContentAccessor(IContentManager contentManager, | |
IAliasService aliasService) { | |
_lookups = new ConcurrentDictionary<string, int?>(); | |
_contentManager = contentManager; | |
_aliasService = aliasService; | |
} | |
public IContent GetContentItemByAlias(string alias, VersionOptions versionOptions = null) { | |
versionOptions = versionOptions ?? VersionOptions.Published; | |
var id = GetContentItemIdByAlias(alias, versionOptions); | |
return id.HasValue ? _contentManager.Get(id.Value, versionOptions) : null; | |
} | |
public int? GetContentItemIdByAlias(string alias, VersionOptions versionOptions = null) { | |
int? id = null; | |
versionOptions = versionOptions ?? VersionOptions.Published; | |
alias = (alias ?? string.Empty).Trim(new[] { '/' }); | |
if (!_lookups.ContainsKey(alias)) { | |
var itemRoute = _aliasService.Get(alias); | |
if (itemRoute != null) { | |
if (itemRoute["Id"] != null) { | |
id = itemRoute["Id"].ToString().ToNullInt(); | |
} | |
else if (itemRoute["blogId"] != null) { | |
id = itemRoute["blogId"].ToString().ToNullInt(); | |
} | |
} | |
_lookups.TryAdd(alias, id); | |
} | |
else { | |
_lookups.TryGetValue(alias, out id); | |
} | |
return id; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like this, thanks for sharing. Just as a heads up in case... I don't know, one thing it doesn't handle is url prefixes.