RMD
RMD

Reputation: 311

Adding parameters to Rest calls

I am doing a REST call. The service url that I want to call should be fetched in the oracle database. I am fetching it using a query and assigning to variable called 'url' in the HomeController. I want to add parameters 'keyname' and 'keyvalue' with this url and use it in REST call. I am fetching parameters also using a query in Home Controller. I am fetching url and keyname and keyvalue in HomeController as,

public async Task<ActionResult> Index(string key, string value){
    url = Reader2.GetValue(1).ToString();
    ----
    keyName = (Reader4.GetValue(1)).ToString();
    keyValue = (Reader4.GetValue(2)).ToString();
---}

I want to use it in RestCall class.

public async Task RunAsync(string name, string value)
        {
        using (var handler = new HttpClientHandler { UseDefaultCredentials = true })
            using (var client = new HttpClient(handler))
            {
var byteArray = Encoding.ASCII.GetBytes("username:password");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                client.BaseAddress = new Uri(HomeController.url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(HomeController.url);
----}

I want to pass keyname and keyvalue parameters with the url in RestCall class.

Upvotes: 0

Views: 104

Answers (1)

Kim C
Kim C

Reputation: 11

As far as I understand your question is you want to do a GET action within query strings. If so, you can use the UriBuilder to build the query string then append to base Url.

For example:

public HttpResponseMessage GetWithParameters(String path, Dictionary<string, string> urlParameters)
{
String parameters = BuildURLParametersString(urlParameters);
HttpResponseMessage response = httpClient.GetAsync(path + parameters).Result;
return response;
}

private String BuildURLParametersString(Dictionary<string, string> parameters)
{
UriBuilder uriBuilder = new UriBuilder();
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
foreach (var urlParameter in parameters)
{
query[urlParameter.Key] = urlParameter.Value;
}
uriBuilder.Query = query.ToString();
return uriBuilder.Query;
}

You can find more example at http://wantmoredomore.com/c-httpclient-to-rest-api-calls/

Hope it useful

Upvotes: 1

Related Questions