Skip to main content

ASP.NET C# helper method to gets the specified key value input from the current HTTP request... in the following order: Cookies, Form, QueryString and ServerVariables.

// Source: Microsoft ASP.NET HttpRequest Class

/// <summary>
/// Gets the specified object from the
/// <see cref="P:System.Web.HttpRequest.Cookies" />,
/// <see cref="P:System.Web.HttpRequest.Form" />,
/// <see cref="P:System.Web.HttpRequest.QueryString" /> or
/// <see cref="P:System.Web.HttpRequest.ServerVariables" /> collections.
/// </summary>
/// <returns>
/// The <see cref="P:System.Web.HttpRequest.QueryString" />
/// <see cref="P:System.Web.HttpRequest.Form" />
/// <see cref="P:System.Web.HttpRequest.Cookies" /> or
/// <see cref="P:System.Web.HttpRequest.ServerVariables" /> collection
/// member specified in the <paramref name="key" /> parameter.
/// If the specified <paramref name="key" /> is not found, then null
/// is returned.
///  </returns>
/// <param name="key">
/// The name of the collection member to get.
/// </param>
public static string GetRequestInput(string key)
{
    var context = HttpContext.Current;
    if (context == null)
    {
        throw new NullReferenceException("context");
    }

    string item = context.Request.QueryString[key];
    if (item != null)
    {
        return item;
    }

    item = context.Request.Form[key];
    if (item != null)
    {
        return item;
    }

    HttpCookie httpCookie = context.Request.Cookies[key];
    if (httpCookie != null)
    {
        return httpCookie.Value;
    }

    item = context.Request.ServerVariables[key];
    if (item != null)
    {
        return item;
    }

    return null;
}