In the blog post prior to this one I discussed the pros and cons of Akismet. This article will discuss how to implement Akismet in your ASP.NET MVC app.
Note: I am currently using ASP.NET MVC 3 with Razor views, just in case that makes any difference.
Step 1: Sign up at Akismet.com and get your API key. (Akismet is free for personal use)
Step 2: Download the .Net 2.0 API library. This works with .NET 4 just fine.
Note: There is no binary to download. You will have to download the zipped C# project, open it in visual studio, and build the project to create Joel.Net.Akismet.dll
.
Step 3: Add a reference to the Joel.Net.Akismet.dll
library in your MVC project.
Step 4: Create a new ActionFilterAttribute
:
public class AkismetCheckAttribute : ActionFilterAttribute
{
public AkismetCheckAttribute(
string authorField,
string emailField,
string websiteField,
string commentField)
{
this.AuthorField = authorField;
this.EmailField = emailField;
this.WebsiteField = websiteField;
this.CommentField = commentField;
}
public string AuthorField { get; set; }
public string EmailField { get; set; }
public string WebsiteField { get; set; }
public string CommentField { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Create a new instance of the Akismet API and verify your key is valid.
Akismet api = new Akismet("-= API KEY HERE =-", "http://CodeTunnel.com", filterContext.HttpContext.Request.UserAgent);
if (!api.VerifyKey()) throw new Exception("Akismet API key invalid.");
//Now create an instance of AkismetComment, populating it with values
//from the POSTed form collection.
AkismetComment akismetComment = new AkismetComment
{
Blog = "http://CodeTunnel.com",
UserIp = filterContext.HttpContext.Request.UserHostAddress,
UserAgent = filterContext.HttpContext.Request.UserAgent,
CommentContent = filterContext.HttpContext.Request[this.CommentField],
CommentType = "comment",
CommentAuthor = filterContext.HttpContext.Request[this.AuthorField],
CommentAuthorEmail = filterContext.HttpContext.Request[this.EmailField],
CommentAuthorUrl = filterContext.HttpContext.Request[this.WebsiteField]
};
//Check if Akismet thinks this comment is spam. Returns TRUE if spam.
if (api.CommentCheck(akismetComment))
//Comment is spam, add error to model state.
filterContext.Controller.ViewData.ModelState.AddModelError("spam", "Comment identified as spam.");
base.OnActionExecuting(filterContext);
}
}
tep 5: Apply it to the appropriate action method. AddComment
in my case:
[HttpPost]
[AkismetCheck("Author", "Email", "Website", "Body")] //Our custom action filter.
public ActionResult AddComment(PostComment newComment)
{
if (ModelState.IsValid)
{
//Do stuff.
}
}
Step 6: Done.
It's that simple!