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
Update:
Thanks for the suggestions, now, the source code for this test is in GitHub
and it also runs and can be tested on Azure:
- http://freewebapi.azurewebsites.net/api/values?p1=Apple&p2=Banana