【问题标题】:Unsupported media type requested when requesting application/json on WCF Data Service在 WCF 数据服务上请求应用程序/json 时请求的媒体类型不受支持
【发布时间】:2012-10-19 10:49:20
【问题描述】:

我正在我现有的类上使用反射提供程序 (http://msdn.microsoft.com/en-us/library/dd728281.aspx) 构建 WCF 数据服务(使用 .net 4.5 VS 2012)。我可以在请求标头中使用“Accept: application/atom+xml”成功访问该服务。但是,在请求标头中将“接受”更改为“应用程序/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;
    }
}

【问题讨论】:

  • 可能出现错误“application/json”
  • Regfor,感谢您的快速回复,这里只是一个错字(已更正),但我的代码中没有。我在我的代码中尝试了很多次,发现只支持 application/atom+xml。跨度>

标签: json wcf wcf-data-services


【解决方案1】:

如果您使用的是 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

【讨论】:

  • 解决了我的问题。谢谢!
【解决方案2】:

tl;dr: 添加请求头

最大数据服务版本:2.0

【讨论】:

    【解决方案3】:

    如果您使用的是较新版本的 WCF 数据服务,您可能需要使用以下 Accept 标头:Accept: application/json;odata=verbose,text/plain

    这允许像 $count 这样的标量查询的纯文本响应,并且还指定 JSON 的详细版本。我正在使用 WCF Data Services 5.3,这是我发现的必要条件。我也见过Accept: application/json;odata=light,但我个人并不需要它,因为详细版本的 odata 运行良好。

    【讨论】:

    • 请注意,WCF 数据服务客户端不支持详细的 JSON 格式,并且在 OData v4(目前正在标准化)中,该格式将完全消失。
    • @JenS 感谢您的提醒。我刚刚发布了a related question,以防你知道答案。
    猜你喜欢
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2015-03-30
    • 2018-10-13
    相关资源
    最近更新 更多