json - 在 WCF 数据服务上请求应用程序/json 时请求的媒体类型不受支持

标签 json wcf wcf-data-services

我正在我现有的类上使用反射提供程序 (http://msdn.microsoft.com/en-us/library/dd728281.aspx) 构建 WCF 数据服务(使用 .net 4.5 VS 2012)。我可以通过请求 header 中的“Accept: application/atom+xml”成功访问该服务。但是,在请求 header 中将“接受”更改为“应用程序/json”时出现错误“请求了不支持的媒体类型”。据我了解,WCF 数据服务支持 JSON,我应该怎么做才能在服务上查询 json 数据?

谢谢

编辑:
我在下面粘贴我的代码:
首先,我定义了 Product 类:

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

然后我定义了我的 ProductContext 类:
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();
        }
    }
}

和我的 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;
    }
}

最佳答案

如果您使用的是 WCF 数据服务 5.0,请查看这篇博文,其中解释了 JSON 支持的变化:http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx

关于json - 在 WCF 数据服务上请求应用程序/json 时请求的媒体类型不受支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972665/

相关文章:

c# - WCF 数据服务是否有任何解决方法来绕过 OData V3 枚举支持的缺失?

jquery - 为什么我的 jquery jsoneach() 循环返回未定义?

json - 招摇的用户界面 : Prettify JSON

c# - 缺少装配引用?

c# - 服务无法在 WCF 中找到其他服务的端点

c# - WCFTestClient 通过禁用 TLS 1.0 和 TLS 1.1 给出错误消息

php - 将 JSON 数据发布到外部 URL

c# - 返回一个已经从 WCF 格式化为 JSON 的字符串

c# - 将 JSON 对象发布到 WCF 服务对象始终为 null

c# - 用于 silverlight 4 + WCF 数据服务的 IAsyncRepository 或 IObservableRepository