Even though @Kiran Challa's answer is correct, there are few situations that you might prefer to get URL parameters directly from the URL. in those scenarios, try this:
using System.Net.Http;
var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs();
string p1Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p1").Value;
string p2Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p2").Value;
string p3Val = allUrlKeyValues.LastOrDefault(x => x.Key == "p3").Value;
Now for the following URL, p1Val will be "Apple", p2Val will be "Banana", and p3Val will be null.
.../api/myController?p1=Apple&p2=Banana
Thanks for the suggestions, now, the source code for this test is in GitHub and it also runs and can be tested on Azure:
The query string key name should match the parameter name of the action:
/api/values?queryString=f
public IEnumerable<string> Get(string queryString)
{
return new string[] { "value3", "value4" };
}
There is one more way to get query string as shown below when you are using wildcard in route or for dynamic routes.
string query = ControllerContext.HttpContext.Request.QueryString.Value;
BONUS:)
string path = ControllerContext.HttpContext.Request.Path.ToUriComponent();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With