Correcting All Raw URLs Inside a String of HTML
If you create a link inside an EPiServer page to another EPiServer page, the link that gets embedded in the HTML is not friendly. It looks something like this:
EPiServer corrects these links very late in the page lifecycle – actually in a response filter after the entire page has been generated. This way, it’s sure to correct links no matter where on the page they might be.
What I noticed, however, is that these links were only getting corrected for Web forms. More specifically, they were only getting corrected for anything with a “text/html” content type.
This was usually fine because I could change the response type, but sometimes it was an issue, especially when doing Ajax callbacks. You often send those back as some plain text format like JSON, and you form the response at the code level, concatening the raw values of properties into a string. Before long, you notice that your links aren’t corrected in blocks of HTML.
It’s not hard to get the friendly URL from a PageData object:
UrlBuilder url = new UrlBuilder(pd.LinkURL);
UrlRewriteProvider.ConvertToExternal(url, somePageData.PageLink, UTF8Encoding.UTF8);
string theFriendlyURl = url.ToString();
This is great to go from a PageData object to a friendly URL. What I found to be much tricker, however, was if I had a big string of HTML with a bunch of embedded links and I needed to correct them all before working with the string.
When I was in Sweden for the Partner Summit, I posed this question to Magnus Stråle. I was awfully grateful when he took the time to dig through EPiServer’s unit tests to find a chunk of code for me. It’s distilled down to this function:
private string CorrectLinks(string rawHtml)
var toExternal = new FriendlyHtmlRewriteToExternal(UrlBuilder.RebaseKind.ToRootRelative);
This will take a string of HTML, correct all the links inside of it, and return another string, ready for insertion into any response, be it text, JSON, or whatever.
Thanks to Magnus for taking the time to help me solve this.