Wednesday, April 22, 2020

How to access the query string in ASP.Net Web Api?

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

No comments:

Post a Comment