Generating a Slug From a String
Posted: October 2, 2009 Filed under: .NET General, Code | Tags: Extension Methods, Slug, Unicode, url Leave a comment »I can’t (and won’t) take full credit for this extension method. The hardcore Unicode stuff is from Michael Kaplan’s blog (jeez, he is hardcore). There is a little danish “stuff” included, for special characters æ, ø and å, which can also be written “ae”, “oe” an “aa”.
public static string ToSlug(this string message)
{
// replace space with -
message = Regex.Replace(message, @"[\s/\\\.,+|_]+", "-");
// normalize the message
message = message.Normalize(NormalizationForm.FormD);
message = message.Replace("ø", "oe").Replace("Ø", "Oe").Replace("æ", "ae").Replace("Æ", "Ae").Replace("å", "aa").Replace("Å", "Aa");
StringBuilder result = new StringBuilder();
for (int i = 0; i < message.Length; i++)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(message[i]);
if (uc != UnicodeCategory.NonSpacingMark)
{
result.Append(message[i]);
}
}
return Regex.Replace(result.ToString().Normalize(NormalizationForm.FormC), @"[^a-zA-Z0-9\-]", "").ToLower();
}
Getting an absolute URL from ASP.NET Webforms
Posted: January 15, 2009 Filed under: ASP.NET | Tags: ASP.NET, url Leave a comment »Related to the post Getting an absolute URL from ASP.NET MVC here is the corresponding ASP.NET Webforms version (not as extension methods):
public static Uri GetBaseUrl(HttpRequest request)
{
Uri contextUri = new Uri(request.Url, request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
public static string GetAbsoluteUrl(HttpRequest request, string relativeUrl)
{
return new Uri(GetBaseUrl(request), VirtualPathUtility.ToAbsolute(relativeUrl)).AbsoluteUri;
}
Getting an absolute URL from ASP.NET MVC
Posted: January 13, 2009 Filed under: ASP.NET MVC | Tags: ASP.NET, ASP.NET MVC, url 4 Comments »I have been in situations where I need to generate an absolute URL to a specific action in an ASP.NET MVC application. The main problem mostly lies in getting the “domain” part of the URL. The only way to do this is to examine the request URL. I came across a very nice method of doing this during an encounter with the dotnetopenid.
public static Uri GetBaseUrl(this UrlHelper url)
{
Uri contextUri = new Uri(url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
public static string ActionAbsolute(this UrlHelper url, string actionName, string controllerName)
{
return new Uri(GetBaseUrl(url), url.Action(actionName, controllerName)).AbsoluteUri;
}