Tuesday, 6 August 2013

Custom ActionFilter with blocking calls, is it an issue? [on hold]

Custom ActionFilter with blocking calls, is it an issue? [on hold]

I have written a custom ActionFilter to query the StopForumSpam.com API to
check if a supplied e-mail address is a known/reported spamming address. I
am using this filter along with a Recaptcha filter to help reduce the
amount of SPAM clients receive.
The code contains two blocking calls - the calls to .Result - and I would
like to know if they could be an issue for the websites. Any other
comments regarding the code are welcome as well.
public class StopForumSpam : ActionFilterAttribute
{
public class SFSResult
{
public class EmailCheckResult
{
public bool Appears { get; set; }
public int Frequency { get; set; }
public DateTime LastSeen { get; set; }
}
public bool Success { get; set; }
public EmailCheckResult Email { get; set; }
}
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{
var emailAddress =
filterContext.HttpContext.Request.Form["ContactUsInfo.EmailAddress"];
HttpClient http = new HttpClient();
http.BaseAddress = new
Uri(System.Configuration.ConfigurationManager.AppSettings["SfsApiUrl"]);
// .Result causes Blocking...
HttpResponseMessage resp = http.GetAsync("?f=json&email=" +
emailAddress).Result;
// SFS sets Content-Type to application/html, so we need to
override that
resp.Content.Headers.ContentType = new
MediaTypeWithQualityHeaderValue("application/json");
// if successful, let's check what StopForumSpam had to say...
otherwise, we let it go through so as to not annoy
// real users... unfortunately spam can still get through then
if (resp.IsSuccessStatusCode)
{
Controller controller = filterContext.Controller as Controller;
if (controller == null)
throw new ApplicationException("Controller must be valid
and of type " + typeof(Controller).ToString());
var formatters = new List<MediaTypeFormatter>() { new
JsonMediaTypeFormatter() };
// .Result causes Blocking...
SFSResult result =
resp.Content.ReadAsAsync<SFSResult>(formatters).Result;
if (result.Success)
{
if (( result.Email != null) && ( result.Email.Appears))
controller.ModelState.AddModelError("SFS", "Sorry, we
can't process your request at this time.");
}
}
base.OnActionExecuting(filterContext);
}
}

No comments:

Post a Comment