Skip to content

Instantly share code, notes, and snippets.

@carlwoodhouse
Last active December 8, 2017 12:45
Show Gist options
  • Save carlwoodhouse/05b2a62c53625b483fce94e85de934b8 to your computer and use it in GitHub Desktop.
Save carlwoodhouse/05b2a62c53625b483fce94e85de934b8 to your computer and use it in GitHub Desktop.
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;
}
}
}
@Hazzamanic
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment