2017-05-23 1 views
-2

JSONを使用して別のAPI( )を呼び出すasp.net mvc5プロジェクトがあり、そのAPIを私のコントローラアクションから呼び出すには、そこで何らかのハッシングを行う必要がある、asp.netでAPIを呼び出す方法MVC5

これは初めてのことですが、JSONでリクエストを送信し、コントローラアクションを使用してJSONでレスポンスを取得する必要があります。

+0

もしかして、あなたのコントローラからasp.net mvc5の別のWEB APIを呼び出すには? –

+0

これをどのように達成できるか説明しているインターネット上の参考文献がたくさんあります。たとえば、これを参照してくださいhttps://levelnis.co.uk/blog/how-do-you-post-to-a-web-api-controller-from-an-mvc-controller –

+0

ええ、私のリモートAPIを呼び出すプロジェクト。 – Abdibrahim

答えて

1

の場合:

   string uri = "yourdomain/api/controller/method; 

       var client = new HttpClient(); 
       var values = new Dictionary<string, string>() 
        { 
         {"username", SecurityHelper.EncryptQueryString(username)}, 
         {"password", SecurityHelper.EncryptQueryString(password)}, 
        }; 
       var content = new FormUrlEncodedContent(values); 
       var response = await client.PostAsync(uri, content); 
       response.EnsureSuccessStatusCode(); 

あなたの方法がある場合はGET:

    string url = "domain/api/controller/method?parameter1=param"; 
        using (var client = new HttpClient()) 
        { 
         HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false); 
         if (response.IsSuccessStatusCode) 
         { 
          var jsonResponse = response.Content.ReadAsStringAsync().Result; 
          bool data = JsonConvert.DeserializeObject<bool>(jsonResponse); 
          return data; 
         } 
        } 
0
 var client = new HttpClient(); 
     var payload = @"{ 
      'CPU': 'Intel', 
      'PSU': '500W', 
      'Drives': [ 
      'DVD read/writer', 
      '500 gigabyte hard drive', 
      '200 gigabype hard drive' 
      ] 
     }"; 

     var content = new StringContent(payload, Encoding.UTF8, "application/json"); 
     var url = {APIEndpoint}; 
     var result = await client.PostAsync(url, content); 

応答解析使用JSON.NET:あなたのメソッドがPOST

JObject joResponse = JObject.Parse(result); 
関連する問題