Retrieving parameters from the query string in the URL in .Net

23 Jul 2013 .Net, C#, Filters, MVC No Comments

Here is a nice easy way to get the individual parameter values from the URL, returning either a NameValueCollection (System.Collections.Specialized.NameValueCollection HttpRequestBase.QueryString) of all parameters in the query string, or a string value of a particular named parameter.

Return a NameValueCollection of all parameters

In a controller

var parameters = HttpContext.Request.QueryString;

In a view

var parameters = HttpContext.Current.Request.QueryString;

In an attribute (filter)

public class MyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var parameters = filterContext.HttpContext.Request.QueryString;
        ...
    }
}

Return a string of an individually named parameter from the query string

In a controller

var value = HttpContext.Request.QueryString["valueName"];

In a view

var value = HttpContext.Current.Request.QueryString["valueName"];

In an attribute (filter)

public class MyAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var value = filterContext.HttpContext.Request.QueryString["valueName"];
        ...
    }
}

Note

When requesting a named parameter, if the named parameter does not exist it will return null (rather than causing an exception).

if (HttpContext.Request.QueryString["valueName"] == null)
{
    // valueName does not exist in the query string
}

Follow my blog with Bloglovin