将参数添加到Rest调用

时间:2018-03-22 03:50:21

标签: c# asp.net-mvc oracle rest

我正在进行REST调用。我想调用的服务URL应该在oracle数据库中获取。我使用查询获取它并在HomeController中分配名为'url'的变量。我想用这个url添加参数'keyname'和'keyvalue',并在REST调用中使用它。我也使用Home Controller中的查询来获取参数。  我在HomeController中获取url和keyname以及keyvalue,

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

我想在RestCall类中使用它。

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);
----}

我想在RestCall类中使用url传递keyname和keyvalue参数。

1 个答案:

答案 0 :(得分:1)

据我所知,您的问题是您想在查询字符串中执行GET操作。如果是这样,您可以使用UriBuilder构建查询字符串,然后附加到基本URL。

例如:

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;
}

您可以在http://wantmoredomore.com/c-httpclient-to-rest-api-calls/

找到更多示例

希望它有用