У меня были некоторые проблемы с решением:
Я использовал код сверху , немного расширил его и закончил с этим:
private static readonly Regex urlRegEx = new Regex(@"(?<!="")((http|ftp|https|file):\/\/[\d\w\-_]+(\.[\w\-_]+)*([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)");
private static readonly Regex quotedUrlRegEx = new Regex(@"(?<!=)([""']|"|')((http|ftp|https|file):\/\/[\d\w\-_]+(\.[\w\-_]+)*([\w\-\.,@?^=%&:/~\+# ])*)\1");
public static MvcHtmlString DisplayWithLinksFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string templateName = null)
{
var encodedHTML = htmlHelper.DisplayFor(expression, templateName);
return MvcHtmlString.Create(ReplaceUrlsWithLinks(encodedHTML.ToHtmlString()));
}
private static string ReplaceUrlsWithLinks(string input)
{
input = input.Replace(@"\\", @"file://").Replace('\\', '/');
var result = quotedUrlRegEx.Replace(input, delegate(Match match)
{
string url = match.Groups[2].Value;
return String.Format("<a href=\"{0}\">{1}</a>", Uri.EscapeUriString(url), ShortenURL(url));
});
return urlRegEx.Replace(result, delegate(Match match)
{
string url = match.ToString();
return String.Format("<a href=\"{0}\">{1}</a>", Uri.EscapeUriString(url), ShortenURL(url));
});
}
private static string ShortenURL(string url)
{
url = url.Substring(url.IndexOf("//", StringComparison.Ordinal) + 2);
if (url.Length < 60)
return url;
var host = url.Substring(0, url.IndexOf("/", StringComparison.Ordinal));
return host + "/…";
}
Очевидно, что не 100% проверено для всех схем URL, но, похоже, работает нормально.
Пример ввода:
"\\02lanpc\abc\def\Bugs in the database.docx"
http://localhost:81/applications/2/?releaseNumber=1.1&buildNumber=2
Выход:
<a href="file://02lanpc/abc/def/Bugs%20in%20the%20database.docx">02lanpc/abc/def/Bugs in the database.docx</a>
<a href="http://localhost:81/applications/2/?releaseNumber=1.1&buildNumber=2">localhost:81/…</a>