locked
$format=xml is not working in OData V4 (Web Api 2.2) with default configuration RRS feed

  • Question

  • User1584005044 posted

    Hi Everyone 

    I just started catching up OData V4 (Web Api 2.2) and facing problem that I am not able to get XML response.  $format=xml is just being ignored and always getting JSON 

    My requirement is  JSON need to be default and XMl should be available on request $format=xml 

    I tried several work around but none work perfectly ,

    Surprisingly If I made XML as Default that I can get JSON as Optional i.e. ($format=xml )

    1. Created two table in database (Customer and Order )
    2. Order has a Foreign key with customer 
    3. Created a Data Model (using EF Code first from DB)
    4. Create Controllers for (Customer and Order )
    5. Modified App Start to Make XMl as Default 

    Any Pointers are greatly appreciated

    Regards

    Ashwini

     

    Here is code details 

    Table Script 

    CREATE TABLE [dbo].[Customer](
    	[CustomerID] [int] IDENTITY(1,1) NOT NULL,
    	[Name] [nvarchar](50) NULL,
    	[Address] [nvarchar](50) NULL,
     CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
    (
    	[CustomerID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    ALTER TABLE [dbo].[Customer]  WITH CHECK ADD  CONSTRAINT [FK_Customer_Customer] FOREIGN KEY([CustomerID])
    REFERENCES [dbo].[Customer] ([CustomerID])
    GO
    
    ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [FK_Customer_Customer]
    
    
    --==================================================================================================================
    CREATE TABLE [dbo].[Order](
    	[OrderNumber] [int] IDENTITY(1,1) NOT NULL,
    	[OrderCount] [int] NULL,
    	[OrderValue] [bigint] NULL,
    	[CustomerID] [int] NULL,
     CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED 
    (
    	[OrderNumber] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    
    ALTER TABLE [dbo].[Order]  WITH CHECK ADD  CONSTRAINT [FK_Order_Customer] FOREIGN KEY([CustomerID])
    REFERENCES [dbo].[Customer] ([CustomerID])
    GO

    App start 

     public static void Register(HttpConfiguration config)
            {
    
                var formatters = ODataMediaTypeFormatters.Create();
                config.Formatters.InsertRange(1, formatters);
               
                GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
    
                
                config.MapODataServiceRoute( "odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
               
            }

    Models

     [Table("Customer")]
        public partial class Customer
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public Customer()
            {
                Orders = new HashSet<Order>();
            }
    
            public int CustomerID { get; set; }
    
            [StringLength(50)]
            public string Name { get; set; }
    
            [StringLength(50)]
            public string Address { get; set; }
    
    
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<Order> Orders { get; set; }
        }
    }
    
        [Table("Order")]
        public partial class Order
        {
            [Key]
            public int OrderNumber { get; set; }
    
            public int? OrderCount { get; set; }
    
            public long? OrderValue { get; set; }
    
            public int? CustomerID { get; set; }
    
            //public virtual Customer Customer { get; set; }
        }
    }
    

    Data Context Class 

        public partial class Model1 : DbContext
        {
            public Model1()
                : base("name=Model12")
            {
                this.Configuration.LazyLoadingEnabled = true;
                this.Configuration.ProxyCreationEnabled = false;
    
                this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
            }
    
            public virtual DbSet<Customer> Customers { get; set; }
            public virtual DbSet<Order> Orders { get; set; }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //modelBuilder.Entity<Customer>()
                //  ;
            }
        }

    Thursday, January 14, 2016 3:56 PM

All replies

  • User-2057865890 posted

    Hi ashwini,

    Based on your description, I tried and I can get both XML and JSON response.

    Please take a look at the following sample.

    WebApiConfig

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
                config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");           
    
            }
        }

    Model

        public class Meeting
        {
            public string Id { get; set; }
            public DateTime MeetingDate { get; set; }
            public string Title { get; set; }
            public string Leader { get; set; }
        }

    MeetingsController

        public class MeetingsController : ApiController
        {
            private readonly IList<Meeting> meetingList;
    
            public MeetingsController()
            {
                meetingList = new List<Meeting>
                {
                    new Meeting { Id = "1", Leader = "Jhon", MeetingDate = new DateTime(2016, 5, 16), Title = "Project discussion" },
                    new Meeting { Id = "2", Leader = "Henary", MeetingDate = new DateTime(2016, 5, 27), Title = "project Planning" },
                    new Meeting { Id = "3", Leader = "Smith", MeetingDate = new DateTime(2016, 6, 1), Title = "Advanced  Technology" },
                    new Meeting { Id = "4", Leader = "Robbin", MeetingDate = new DateTime(2016, 6, 17), Title = "Maintenance" },
                    new Meeting { Id = "5", Leader = "Carter", MeetingDate = new DateTime(2016, 6, 27), Title = "Company Forum" },
                    new Meeting { Id = "6", Leader = "Rollin", MeetingDate = new DateTime(2016, 5, 21), Title = "Selling product" }
                };
            }
    
    
            public IQueryable<Meeting> Get()
            {
                return meetingList.AsQueryable();
            }
        }

    XML

    JSON

    Best Regards,

    Chris Zhao

    Monday, January 18, 2016 4:28 PM