user7739271
user7739271

Reputation:

How to get all url parameters in asp.net mvc?

My test url:

localhost:61578/?type=promotion&foo=bar

I usually use this way to get the value of type parameter:

public IActionResult Index(string type)
{
    // type = "promotion"
}

My question: How to detect all parameters in the url? I want to prevent to access the page with some unknown parameter.

Something like this:

public IActionResult Index(string type, string foo)
{
    if (!string.IsNullOrEmpty(foo))
    {
        return BadRequest(); // page 404
    }
}

The problem is: I don't know exactly the name what user enters. So, it can be:

localhost:61578/?bar=baz&type=promotion

Upvotes: 1

Views: 5084

Answers (1)

Svek
Svek

Reputation: 12858

You can use the HttpContext Type to grab the query string

var context = HttpContext.Current;

then, you can grab the entire query string:

var queryString = context.Request.QueryString

// "bar=baz&type=promotion"

or, you can get a list of objects:

var query = context.Request.Query.Select(_ => new
{
    Key = _.Key.ToString(),
    Value = _.Value.ToString()
});

// { Key = "bar", Value = "baz" }
// { Key = "type", Value = "promotion" }

or, you could make a dictionary:

Dictionary<string, string>queryKvp = context.Request.GetQueryNameValuePairs()
    .ToDictionary(_=> _.Key, _=> _.Value, StringComparer.OrdinalIgnoreCase);

// queryKvp["bar"] = "baz"
// queryKvp["type"] = "promotion"

Upvotes: 5

Related Questions