การเรียก POST ด้วย HttpWebRequest

ถ้าเรียก HttpWebRequest แล้วเจอ error

The request was aborted: Could not create SSL/TLS secure channel.  

[Main] System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.HttpWebRequest.GetResponse()

ให้แก้ไขด้วยการวาง ServicePointManager

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// SecurityProtocolType.Tls
// SecurityProtocolType.Tls11
// SecurityProtocolType.Ssl3;

ไว้ก่อน HttpWebRequest

//createing HttpWebRequest after ServicePointManager settings
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")

ตัวอย่าง

ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com/api/")
request.ContentType = "application/json";
request.Method = "POST";

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    People movReq = new People();

    People.username = "user1";
    People.password = "paas1";
    People.xxx = "xxx";
    
    string jsonReq = JsonConvert.SerializeObject(movReq);
    log.Info(string.Format("Request: jsonString='{0}'", jsonReq));

    streamWriter.Write(jsonReq);
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
MOVRealTimeResponse resp;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
    log.Info(string.Format("Response: string='{0}'", result));

    resp = JsonConvert.DeserializeObject<MOVRealTimeResponse>(result);
}