Search code examples
c#apisoapfedex

C# Fedex SOAP API - Get Shipping Label


I'm trying to use the Fedex API to send SOAP requests and get shipping labels. The developer documentation on Fedex's website isn't very helpful. Does anyone have any sample code showing how to get shipping labels from your requests? Below is what I'm trying - looks like my request works, but my filestream returns a broken pdf. Unless Fedex is responding to my request incorrectly I'm at a loss for where to continue looking.

        FedExHelper fedExHelper = new();

        // builds the xml for the request 
        var parsedXml = fedExHelper.BuildShipmentRequest();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://ws.fedex.com/web-services");
            client.DefaultRequestHeaders.Add("Accept", "image/gif, image/jpeg, image/pjpeg, text/plain, text/html, */*"); // for Accept header                

            HttpRequestMessage request = new();
            request.Method = HttpMethod.Post;
            request.Content = new StringContent(parsedXml);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
            var response = client.Send(request);

            return new FileStreamResult(await response.Content.ReadAsStreamAsync(), "application/pdf")
            {
                FileDownloadName = "test.pdf"
            };
        }

Also tried the below after reading the xml response. There's a label node that contains a base64 image. Decoding the base64 string still downloads a broken pdf.

var responseText = FedExHelper.SampleResponseText();

            XDocument xml = XDocument.Load(new StringReader(responseText));
            var label = xml.Root.Descendants().Where(x => x.Name.LocalName == "Label").FirstOrDefault();
            var labelParts = label.Descendants().Where(x => x.Name.LocalName == "Parts").FirstOrDefault();
            var image = labelParts.Descendants().Where(x => x.Name.LocalName == "Image").FirstOrDefault();

            byte[] bytes = Convert.FromBase64String(image.Value);
            MemoryStream stream = new(bytes);

            return new FileStreamResult(stream, "application/pdf")
            {
                FileDownloadName = "test.pdf"
            };

Solution

  • @Charleh you were absolutely correct. I had the incorrect ImageType value set in the xml I was posting. I can now return PDF labels.

    For anyone else looking at this:

    I had ZPLII set as the ImageType. This should have been PDF. I was adapting my code from an old dBase program, having no knowledge of working with the Fedex API.

    Fedex API ImageType