2016-07-25 35 views
1

我有一個Web API,我可以通過瀏覽器成功訪問: -C#POST請求的WebAPI使用控制檯程序

https://127.0.0.1:8443/ncrApi

我試圖創建在C#中使用VS2015到一個簡單的控制檯程序發送數據並使用http POST接收響應。

這是我到目前爲止有: -

using System; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Threading.Tasks; 

namespace WebSample 
{ 

    class ApiSendData 
    { 
     public string ApiFunction { get; set; } 
     public string DppName { get; set; } 
     public string ClearData { get; set; } 
     public string DppVersion { get; set; } 
    } 



    class Program 
    { 
     static void Main(string[] args) 
     { 
      // The Main function calls an async method named RunAsync 
      // and then blocks until RunAsyncc completes. 
      RunAsync().Wait(); 
     } 

     static async Task RunAsync() 
     { 
      using (var client = new HttpClient()) 
      { 
       // This code sets the base URI for HTTP requests, 
       // and sets the Accept header to "application/json", 
       // which tells the server to send data in JSON format. 
       client.BaseAddress = new Uri("https://localhost:8443/ncrApi"); 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 


       // HTTP POST 
       var datatobeSent = new ApiSendData() 
            { 
             ApiFunction ="NcrSecureData", 
             DppName ="CSampleCustomer", 
             DppVersion ="Latest", 
             ClearData ="1234567890" 
            }; 

       HttpResponseMessage response = await client.PostAsJsonAsync("ncrApi", datatobeSent); 

       if (response.IsSuccessStatusCode) 
       { 
        // Get the URI of the created resource. 
        Uri ncrUrl = response.Headers.Location; 

        // do whatever you need to do here with the returned data // 


       } 
      } 
     } 
    } 
} 

但是我對HttpResonseMessage響應說法得到一個錯誤.... {「發送請求時發生錯誤。」} { 」請求被中止:無法創建SSL/TLS安全通道。「}

我懷疑這是因爲我沒有正確理解client.BaseAddress和HttpResponseMessage響應語句。

這是我一直在關注: - http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

+0

附加註釋: - 1)我關閉SSL,併成功連接到端口8080上的web api。 2)我成功地通過我的代碼連接到其他SSL api。 似乎C#代碼沒有連接到SSL連接ncrApi ..任何想法爲什麼? – Philo

回答

1

,因爲最後的地址是您baseAddress +帖地址你可能會得到一個錯誤,那就是:http://localhost:8443/nrcApi/nrcApi,不存在

試着改變你的client.BaseAddress到:

client.BaseAddress = new Uri("https://localhost:8443/"); 

對於SSL連接錯誤,請嘗試生成一個受信任的證書: Make https call using httpclient

+0

謝謝。我嘗試了同樣的錯誤。但是這次我關閉了SSL。並剛剛連接到本地主機:8080/ncrapi和工作。我嘗試連接到其他SSL API,我的程序已成功連接到它們 – Philo

+0

並且您是否正確配置了您的ncrapi端點以接受端口8443上的傳入SSL連接?這可能是一些與您的端點相關的服務器端問題。 – Forlani

+0

對我來說似乎也是這樣。我如何檢查我的終點配置... – Philo