Using Images in the BlogEngine Comments

Most of the web applications will not let you use HTML as form input for security reasons. And this is why BlogEngine has BBCode extension - to provide you with ability to define which HTML tags you want visitors be able to use. But it has it's own limitations and can't handle some of the HTML tags without little overhead. For example, I wanted to let visitors to use images in their comments, so I went to extension manager/BBCode and defined [img] code. Problem here is that image tag has specific syntax and BBCode does not set to handle it. I had to modify Parse method to process image tag properly. All I did is added a check to see if code is "img" and, if it is, I use custom parsing. Otherwise BBCode uses default code processing.

if (code == "img")
{
  string regex = @"\[img\].*\[/img\]";
  MatchCollection matches = Regex.Matches(body, regex);
  if (matches.Count > 0)
  {
    foreach (Match match in matches)
    {
      string imgSrc = match.Value.Replace("[img]", "").Replace("[/img]", "").Trim();
      string imgTag = string.Format("<img title=\"\" src=\"{0}\" />", imgSrc);
      body = body.Replace(match.Value, imgTag);
    }
  }
}
else ...

One more thing. Because visitors can not upload images to the site, all images suppose to be on the internet and have "http:" or "www" in the source path. And BlogEngine has "ResolveLinks" extension that will automatically turn everything with "http:", "www" etc. into the hyperlinks in the comments. That is great, but obviously I need to ask this extension leave alone my images.

if (e.Body.Contains("src=\"" + match.Value) || e.Body.Contains("[img]" + match.Value))
      continue;

With this taken care of, everything seems to be working just fine. Now if you want to illustrate your point with image in the comment, just type in path to the image, select it and click BBCode "img" button.

bbcode.zip

About RTUR.NET

This site is all about developing web applications with focus on designing and building open source blogging solutions. Technologies include ASP.NET Core, C#, Angular, JavaScript and more.