为所有控制器设置AllowedQueryOptions = AllowedQueryOptions.All

时间:2016-05-30 12:24:41

标签: odata asp.net-web-api2

我有一个Web API项目,我希望允许调用者在所有控制器上使用所有不同的查询选项。

this threadthis thread的启发,我在WebApiConfig.Register方法中添加了以下代码:

    public static void Register(HttpConfiguration config)
    {
        //[already working configuration code]


        //Allow for $format parameter to OData queries
        config.Filters.Add(new EnableQueryAttribute()
        {
            AllowedQueryOptions = AllowedQueryOptions.All
        });
    }

代码编译并运行,但是当我尝试将$ format参数添加到查询时,我得到了与之前相同的异常:

Query option 'Format' is not allowed. To allow it, set the 'AllowedQueryOptions' property on EnableQueryAttribute or QueryValidationSettings.

为什么WebApiConfig中的AllowedQueryOptions设置没有为所有控制器注册?

1 个答案:

答案 0 :(得分:1)

您在Controller的方法中是否同时具有[EnableQuery]属性和ODataQueryOptions参数?只需使用[EnableQuery]属性,它会在您返回结果后应用ODataQueryOption,并且默认情况下允许格式化。

https://github.com/OData/WebApi/blob/master/OData/src/System.Web.OData/OData/EnableQueryAttribute.cs

如果你需要ODataQueryOptions参数,那么删除[EnableQuery]属性,创建你自己的validatasetting,事情就行了。