Question

I like a lot how the HttpClient is architectured - but I can't figure out how to add a "not quite standard" media type to be handled by the XmlSerializer.

This code:

var cli = new HttpClient();
cli
    .GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
    .ContinueWith(task =>
    {
        task.Result.Content.ReadAsAsync<Feed>();
    }); 

works fine when pointed to atom feeds that have Content-Type of "text/xml", but the one in the example fails with the "No 'MediaTypeFormatter' is available to read an object of type 'Feed' with the media type 'application/atom+xml'" message. I tried different combinations of specifying MediaRangeMappings for the XmlMediaTypeFormatter (to be passed as an argument to ReadAsAsync) but with no success.

What is the "recommended" way to configure the HttpClient to map "application/atom+xml" and "application/rss+xml" to XmlSerializer?

Was it helpful?

Solution

Here is the code that works (credits to ASP.net forum thread):

public class AtomFormatter : XmlMediaTypeFormatter
{
    public AtomFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/atom+xml"));
    }

    protected override bool CanReadType(Type type)
    {
        return base.CanReadType(type) || type == typeof(Feed);
    }
}

var cli = new HttpClient();
cli
    .GetAsync("http://stackoverflow.com/feeds/tag?tagnames=delphi&sort=newest")
    .ContinueWith(task =>
    {
        task.Result.Content.ReadAsAsync<Feed>(new[] { new AtomFormatter });
    }); 

Still, would like to see a solution without subclassing XmlMediaTypeFormatter - anybody?

OTHER TIPS

The problem is that you are trying to convert the result straight to Feed. As error is clearly saying, it cannot figure our how to convert the application/atom+xml into Feed.

You would have to perhaps return as XML and then use and XmlReader to initialise your Feed.

Alternative is to provide your own media formatter - and implementation which encapsulates this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top