Search code examples
c#jsonasp.net-web-apiodata

Web API using Odata returns BSON while expecting Response as JSON


I literally followed this tutorial, http://jerther.blogspot.com/2014/11/aspnet-web-api-2-help-pages-odata_28.html

Excepting the return format as JSON but not sure how am getting back BSON, am new to BSON never heard about.

OData, WebAPI, EF (repository pattern)is what am using. Any suggestions on how to get back JSON instead of BSON.

Here is my Code, what i did so far

WebApiConfig:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            // config.SuppressDefaultHostAuthentication();
            // config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes           
            // Remove the XML formatter
            config.Formatters.Remove(config.Formatters.XmlFormatter);                
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/v1/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

ODataConfig.cs - used it in the routeConfig.cs

 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes(); //This has to be called before the following OData mapping, so also before WebApi mapping
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Item>("Item");
            config.MapODataServiceRoute("ODataRoute", "api", builder.GetEdmModel());
        }

RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Controller.

        [EnableQuery]
        [ODataRoute]
        public IQueryable<Item> GetItem()
        {
            var result = _cRepository.GetAll();            
            return result.AsQueryable();
        }

Response


Solution

  • My Controller was referencing to System.Web.Http.OData, uninstalled all the nuget packages related to Odata,WebAPI and reinstalled. Referenced Controller to System.Web.OData and everything looks good now returns JSON. Thanks a lot for all your responses.