带有 post 的 C# HTTPS 请求

标签 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

最佳答案

事实证明,因为 https 在服务器端,所以根本不需要任何策略或安全代码!所以我可以使用 HTTP request with post 的方法 3

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

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

关于带有 post 的 C# HTTPS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30583425/

相关文章:

asp.net - Angular 5 不会发回身份验证 cookie

amazon-web-services - 将 Heroku SSL (ACM) 与 AWS S3/Cloudfront 一起使用

ssl - Jetty - .cer/.p7b - 无套件密码(没有共同的密码套件)

php - ssl 证书问题 : unable to get local issuer certificate xampp

c# - 在 vb.net 中隐式实例化的对象?

c# - 使用安全 key C# 进行 DES 编码

c# - 泛型/JSON JavaScriptSerializer C#

c# - 从后面的代码添加多个内联样式

c# - 在 Linq 组中查找最大和最小 DateTime

c# - InvalidCastException : Unable to cast object of type 'System.Decimal' to type 'System.String'