Unsupported media type requested when requesting application / json in WCF data service

I am creating a WCF data service (with .net 4.5 VS 2012) using the Reflection Provider (http://msdn.microsoft.com/en-us/library/dd728281.aspx) for existing classes. I can successfully access the service using "Accept: application / atom + xml" in the request header. however, when I change the "Accept" to "application / json" in the request header, I received the error "Unsupported media type." As I found out, the WCF data service supports JSON, what should I do to enable json data request in the service?

thanks

Edit: I embed my code below: I first defined the product class:

[DataServiceKeyAttribute("Id")] public class Product { public int Id { get; set; } public int Price { get; set; } public string Name { get; set; } } 

then I have a ProductContext class:

 public class ProductContext { private List<Product> products = new List<Product>(); public ProductContext() { for (int i = 0; i < 100; i++) { var product = new Product(); product.Id = i; product.Name = "ID - " + i.ToString(); product.Price = i + 100; products.Add(product); } } public IQueryable<Product> Products { get { return products.AsQueryable(); } } } 

and my ProductService.svc.cs

 [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class ProductsService : DataService<ProductContext> { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc. // Examples: config.SetEntitySetAccessRule("Products", EntitySetRights.AllRead); //config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3; } } 
+4
source share
3 answers

If you use WCF Data Services 5.0, check out this blog post explaining the changes to JSON support: http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to -application-json-in-wcf-ds-5-0.aspx

+4
source

tl; dr: add request header

MaxDataServiceVersion: 2.0

+2
source

If you are using a newer version of WCF data services, you may need to use the following Accept header: Accept: application/json;odata=verbose,text/plain

This allows you to send text responses for scalar requests such as $count , as well as specify a detailed version of JSON. I use WCF Data Services 5.3, and this is what I consider necessary. I also saw Accept: application/json;odata=light , but I personally do not need this because the verbose version of odata is working fine.

+2
source

Source: https://habr.com/ru/post/1440756/


All Articles