A day with .Net

My day to day experince in .net

Asynchronous Logging ASP.NET

Posted by vivekcek on March 8, 2012

Hi Friends if you want to track who is using your website you can try out an asynchronous request logging using Task Parallel library.The library code is given below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Text.RegularExpressions;

namespace TSecure
{

public class Logger
{

private static bool _denyBots = false;

private static void DenyAccess(HttpApplication app)
{
app.Response.StatusCode = 0x191;
app.Response.StatusDescription = "Access Denied";
app.Response.Write("401 Access Denied");
app.CompleteRequest();
}

private static bool IsCrawler(HttpRequest request)
{
bool isCrawler = request.Browser.Crawler;
if (!isCrawler)
{
Regex regEx = new Regex("Slurp|slurp|ask|Ask|Teoma|teoma");
isCrawler = regEx.Match(request.UserAgent).Success;
}
return isCrawler;
}

private static void _LogRequest(HttpApplication app)
{
HttpRequest request = app.Context.Request;

bool isCrawler = IsCrawler(request);
string userAgent = request.UserAgent;
string requestPath = request.Url.AbsolutePath;
string referer = (request.UrlReferrer != null) ? request.UrlReferrer.AbsolutePath : "";
string userIp = request.UserHostAddress;
string isCrawlerStr = isCrawler.ToString();
/*  @RemoteIp varchar(50),
@UserAgent varchar(2000) ,
@RequestPath varchar(2000),
@Referer varchar(2000),
@IsCrawler varchar(5) */
//Database code

if (isCrawler && _denyBots)
{
DenyAccess(app);
}

}

public static void LogRequest(HttpApplication app)
{
Task.Factory.StartNew(() => _LogRequest(app));
}

}
}

Now in the Global.asax file of your application,call library via the below code in Prerequisite event

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
TSecure.Logger.LogRequest(sender as HttpApplication);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s