0 Replies - 1050 Views - Last Post: 26 February 2008 - 06:33 PM

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Check for valid HttpRequest

Posted 26 February 2008 - 06:33 PM

Description: This snippet is for use in a class file (not a code behind class file). Pass the method your HttpRequest Object and the domain you're looking for, it will then search that HttpRequest Object's ServerVariables for a valid HTTP_REFERER. Check the "Sample Usage" portion for how to implementThis is a snippet I use for making sure a page request is coming from my domain, and that someone isn't trying to hijack my site or page.
//Namespace Reference
using System.Web;
using System.Collections.Specialized;


#region IsValidRequest
/// 
/// method for determining if this page was called from a valid
/// domain or if someone is trying to hijack this page
/// 
/// True/False
public bool IsValidRequest(System.Web.HttpRequest request,string domain)
{

    //NameValueCollection object for holding the server variables
    NameValueCollection vars = request.ServerVariables;
    string temp = vars.Get("HTTP_REFERER");
    //make sure the referer isnt empty, if it's 
    //empty this isn't a valid request
    if (!(string.IsNullOrEmpty(temp)))
    {
        //ok, so its not empty, now lets make sure the user
        //is coming from a valid page
        if (!(temp.Contains(domain)))
        {
            //not a valid request so return false
            return false;
        }
        else
        {
            //request originated on a valid page so return true
            return true;
        }
    }
    else
    {
        //HTTP_REFERER is empty so this isn't a valid request, return false
        return false;
    }

}
#endregion

//Sample Usage

//replace YourClass with the name of the class where this resides
YourClass check = new YourClass();

//now check the validity
if(!(check.IsValidRequest(Request,"yourdomain.com")))
{
    Response.Redirect("http://www.yoursite.com");
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1