Search code examples
c#c#-5.0dotnet-httpclientflurl

How to do XML POST with FlUrl


FlUrl does a great job in dealing with Json/UrlEncoded requests. However, the documentation doesn't really point out how to handle other request types such as text/xml.

What's the best way to do an XML POST using FlUrl?

This (accessing underlying HttpClient) kinda defeats the purpose of using FlUrl since you need to build the URI and content again:

var result = await "http://someUrl"
                   .AppendPathSegment(pathSegment)
                   .SetQueryParam("name", name)
                   .WithBasicAuth(_userName, _apiToken)
                   .HttpClient
                   .PostAsync(<uri>, <content>);

Solution

  • XML support is not baked in yet, but this is logged and is one of the few remaining features I'd like to have in place for Flurl.Http 1.0. (Surprisingly, no one's requested it until now.)

    In the mean time, Flurl is pretty easy to extend, and you could add this support yourself via extension methods. This should be all you need to post an XML string fluently:

    public static class FlurlXmlExtensions
    {
        // chain off an existing FlurlClient:
        public static async Task<HttpResponseMessage> PostXmlAsync(this FlurlClient fc, string xml) {
            try {
                var content = new CapturedStringContent(xml, Encoding.UTF8, "application/xml");
                return await fc.HttpClient.PostAsync(fc.Url, content);
            }
            finally {
                if (AutoDispose)
                    Dispose();
            }
        }
    
        // chain off a Url object:
        public static Task<HttpResponseMessage> PostXmlAsync(this Url url, string xml) {
            return new FlurlClient(url, true).PostXmlAsync(xml);
        }
    
        // chain off a url string:
        public static Task<HttpResponseMessage> PostXmlAsync(this string url, string xml) {
            return new FlurlClient(url, true).PostXmlAsync(xml);
        }
    }
    

    UPDATE:

    I decided not to include XML support in Flurl, largely because a community member stepped up and created a great extension library for it:

    https://github.com/lvermeulen/Flurl.Http.Xml