0

Is it possible to remove 1 query param value in a simple way? (I'm thinking about recreating the list of values without the value we want to remove using RouteValueDictionary and IUrlHelper.ActionContext.HttpContext.Request.Query but I'm hoping there is a simpler way).

Example:

Original query: localhost:5555/search?cat=none&cat=cat1&cat=cat2

Wanted query (removing cat1): localhost:5555/search?cat=none&cat=cat2

Haytam
  • 4,643
  • 2
  • 20
  • 43
  • Where in the Asp.Net pipeline do you expect this to occur? –  May 09 '18 at 20:41
  • @Amy I don't understand your question. – Haytam May 09 '18 at 20:43
  • Do you know what the Asp.Net pipeline *is*? –  May 09 '18 at 20:43
  • Nope. Do I need to know what it is to do a "simple" task like this? – Haytam May 09 '18 at 20:44
  • The answer depends on when you expect this to occur. You can write an Owin middleware, use a Web API action filter, use a Web API delegating handler, do it in a Web API controller itself... how you do it can affect everything hosted in Owin, or just Web API, or Web API and some other set of components. –  May 09 '18 at 20:46
  • Oh, now I understand. I want to use it in a controller (I'm doing a filter system and I want to remove a certain filter from the query). – Haytam May 09 '18 at 20:50

1 Answers1

2

One way of doing this inside a controller's action method would be to do the following:

var queryParms = Request.GetQueryNameValuePairs();

GetQueryNameValuePairs is an extension method found in the System.Net.Http namespace.

queryParms is an IEnumerable<KeyValuePair<string, string>>. To filter it you can use some LINQ:

var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => kvp.Key != "excluded key");

To filter by key/value pair:

var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => kvp.Key != "excluded key" && kvp.Value != "excluded value");

This gives you a list of key/value pairs excluding the undesired query parameter. If you wanted to exclude a list of keys, you can use the following variation of the above:

var excludedKeys = new[] { "excluded a", "excluded b", "etc" };
var queryParms = Request
    .GetQueryNameValuePairs()
    .Where(kvp => !excludedKeys.Contains(kvp.Key));

If you need to change or replace a query parameter value:

var queryParms = Request.GetQueryNameValuePairs();
var cat = queryParms.FirstOrDefault(x=> x.Key == "cat");
if (cat != null && cat.Value == "cat1")
{
    cat.Value = "none";
}
// other stuff with query parms

Once you have your query parameters the way you want them, you'll need to reconstruct the URL. For this I turn you to a very good answer to another question:

https://stackoverflow.com/a/1877016/47589