Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsupported media type requested when requesting application/json on WCF Data Service

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

Thanks

Edit: I paste my code below: first I have the Product class defined:

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

then I have my ProductContext class defined:

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;
    }
}
like image 853
Shuping Avatar asked Feb 18 '23 19:02

Shuping


2 Answers

If you're using WCF Data Services 5.0, takes a look at this blog post which explains the changes in JSON support: http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx

like image 163
Vitek Karas MSFT Avatar answered May 13 '23 20:05

Vitek Karas MSFT


tl;dr: add a request header of

MaxDataServiceVersion: 2.0

like image 32
Lee Richardson Avatar answered May 13 '23 21:05

Lee Richardson