WCF Web API, Hammock and WP7 Woes
Facing an interesting issue when I am using WCF Web API with Hammock and WP7. As you know, WCF Web API allows you to change the response type based on what you specify in the Accept header. For e.g. if you send Accept:application/json, the response is JSON, if you specify application/xml you get XML and so on.
So I created my Web API which works perfectly fine from a Web Browser. As expected I get the types I want. Hwoever, when I use this from WP7, it doesn't matter what the Accept header is, it looks like WP7 replaces it to / and I only get back XML.
I know for a fact that it isn't Hammock that is the issue because I tried with Facebook Graph API. If I change the Accept to say: application/hello, I get a bad request er开发者_开发知识库ror. However, when I do that with WP7 in C# code, I get absolutely no errors and the return type is XML irrespective of what I send.
To circumvent this issue, I created a JSON.Net Serializer in my WCF Web API. Everything worked great until I started using HttpResponseMessage in my methods as return types. Now even though i have a JSON serializer, I get XML for all methods where I use the HttpResponseMessage.
As you can see, I am in lala land now.
Can anyone provide any feedback?
Any help is highly appreciated.
I ran into this and posted this issue on CodePlex. It's been fixed if you pull the latest source, although Nuget hasn't been updated yet. You should then be able to remove the xml formatter or clear the built in formatters and add the one you want. Another workaround that I found was to clear the built in formatters and create a custom media type formatter that mapped to / accept type.
Update: this has been fixed with WCF Web API Preview 6 now on nuget.
The WCF WebApi lets you specify the format using the querystring if you want to. You need to update the configuration with QueryStringMapping in addition to the RequestHeaderMapping that is there by default.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var config = routes.GetDefaultHttpConfiguration();
var jsonFormatters = config.Formatters.Where(f => f.SupportedMediaTypes.Any(mt => mt.MediaType == "application/json"));
jsonFormatters.ToList().ForEach(f => f.MediaTypeMappings.Add(new QueryStringMapping("format", "json", "application/json")));
routes.MapServiceRoute<BooksService>("books", config);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
精彩评论