带帖子的C#HTTPS请求

时间:2015-06-01 21:15:50

标签: c# asp.net ssl https httpwebrequest

我希望获得HTTPS的完整示例答案,如答案 HTTP request with post特别是方法3.具体包括上下文中使用的安全策略。无论什么时候都没有证书,什么时候没有证书。在我的示例中,我没有真正的证书,但必须使用HTTPS。 我想知道我是否有另一个初学者错误。代码如下(链接更改为假货) 我从这里开始遵循HTTP的步骤:https://msdn.microsoft.com/en-us/library/debx8sh9%28v=vs.110%29.aspx

有关HTTPS帖子的其他答案,无论是在StackOverFlow还是在外部,都指向过时的安全类,或者是only a partial example。我认为其他初学者也会参考更新的答案和完整的例子。

此处的C#代码返回500,但我需要确信我的安全策略调用不是原因 谢谢你的帮助

using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Security.Cryptography.X509Certificates;

namespace GradeSync

{


/* HTTP POST

The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.

REQUEST:
POST /webservices/PspServices.asmx/UpdateGradingSheet HTTP/1.1
Host: itech.psp.org
Content-Type: application/x-www-form-urlencoded
Content-Length: length

UserId=string&LessonId=string&Marks=string&ClassId=string

RESPONSE: 
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">string</string>
 */



    public class PostGradesViaWebRequestPost
    {
        // https://stackoverflow.com/questions/5648596/call-webservice-from-c-sharp-application-using-ssl


        /// public bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        ///{
        ///    Console.WriteLine(sslPolicyErrors);  // Or whatever you want to do...
        ///    return true;
        ///}

        public static void Main()
        {

        string gradesURI = 

        "https://itech.psp.org/webservices/PspServices.asmx/UpdateGradingSheet";

        string userId  = "300810060";   // 300810060 = Dorinda Bex ; 300835525 = Rachel Bess
        string lesson  = "L1";          // Lesson #
        string points  =  "9";          // Review score
        string classId = "432462";     // 432462 = Independent Study 2014 - Sec.2 ; 432525 = Modesto, CA Spring 2015

        // https://stackoverflow.com/questions/12506575/how-to-ignore-the-certificate-check-when-ssl
        System.Net.ServicePointManager.ServerCertificateValidationCallback +=
            delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true; // **** Always accept
            };
        //// goes with policy System.Net.ServicePointManager.ServerCertificateValidationCallback = policy.ValidateServerCertificate;

        //https://msdn.microsoft.com/en-us/library/debx8sh9%28v=vs.110%29.aspx

        // 1  Create a request using a URL that can receive a post. 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gradesURI);  /// new
        //xxWebRequest rqst = HttpWebRequest.Create(gradesURI);

        //WebRequest request = WebRequest.Create( gradesURI );

        // 2
        request.Credentials = CredentialCache.DefaultCredentials;
        request.ProtocolVersion = HttpVersion.Version11;
        /// not needed?  ((HttpWebRequest)request).UserAgent = ".NET Framework Exa
        /// mple Client";

        // 3 Set the Method property of the request to POST.
        request.Method = "POST";

        // 4 Set the ContentLength property of the WebRequest.
        // Create POST data and convert it to a byte array.
        string postData = "Userid="+userId + "&Lesson=" + lesson + "&Marks="+points + "&ClassId="+classId;
        byte[] byteArray = Encoding.UTF8.GetBytes (postData);

        // 5 Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";   // OK right type

        //  Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // 6 Get the request stream.
        Stream dataStream = request.GetRequestStream ();

        // 7 Write the data to the request stream.
        dataStream.Write (byteArray, 0, byteArray.Length);

        // 8 Close the Stream object.
        dataStream.Close ();


        //  Response  /////////////////////////////////////////////
        // 9 Get the response.
        WebResponse response = request.GetResponse();

        // 10 Display the status
        Console.WriteLine (((HttpWebResponse)response).StatusDescription);

        // 11 Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream ();   // from example

        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader (dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd ();
        // Display the content.
        Console.WriteLine (responseFromServer);

        // Clean up the streams.
        reader.Close ();
        dataStream.Close ();

        // 12
        response.Close();


        }  // end main
    }  // end class
}  // end namespace

1 个答案:

答案 0 :(得分:1)

原来因为https在服务器端,所以根本不需要任何策略或安全代码!所以我可以使用HTTP request with post

的方法3

我的问题是拼写错误(Lesson not LessonId),但作为REST初学者,我认为它是HTTPS和安全策略。

现在想知道何时需要安全证书? (可能回答)但这可能是更好的问题。初学者需要提示才能找到正确的问题。