简体   繁体   中英

Post xml using HttpClient in C#

I have a problem with passing xml file from client to api. I use HttpClient to connect. My code:

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        /*var serializer = new XmlSerializer(typeof(InitUploadType));
        serializer.Serialize(data);*/
        XmlDocument doc = new XmlDocument();
        doc.Load("initupload-sign.xml");

        WebRequestHandler handler = new WebRequestHandler();
        X509Certificate2 certificate = new X509Certificate2("cert.crt");
        handler.ClientCertificates.Add(certificate);


        HttpClient client = new HttpClient(handler);
        client.BaseAddress = new Uri("https://test-e-dokumenty.mf.gov.pl");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));

        var response = client.PostAsJsonAsync<XmlDocument>("/api/Storage/InitUploadSigned", doc).Result;

        return response.ToString();

I am receiving Bad Request 400.

Can you please try the below code I have modified?

            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            /*var serializer = new XmlSerializer(typeof(InitUploadType));
            serializer.Serialize(data);*/
            XmlDocument doc = new XmlDocument();
            doc.Load("initupload-sign.xml");

            WebRequestHandler handler = new WebRequestHandler();
            X509Certificate2 certificate = new X509Certificate2("cert.crt");
            handler.ClientCertificates.Add(certificate);

            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri("https://test-e-dokumenty.mf.gov.pl");
            client.Headers.Set("Content-Type", "application/xml");
            var response = client.UploadString(path, doc.OuterXml);

            return response.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM