2016-07-25 75 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