LoginSignup
0
1

More than 5 years have passed since last update.

ASP.NET Web APIのOData v4でつまづいたところ

Posted at

基本的にはASP.NET Web API の OData v4 のサポートを参考にしていたが、詰まったところがあったので、メモ。

クエリオプションを付けるとエラーになる

初期設定とContoller側の設定を両方やらないと効かない場合がある。
初期設定で全般的な使用許可を与えて、個別に設定するイメージかな?

初期設定

追加したいクエリオプションが\$count、\$filter、\$orderby、\$expand、\$selectの場合には、WebApiConfig.csで、各種オプションを有効にする。

WebApiConfig.cs
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            // エンティティを追加
            builder.EntitySet<Customer>("Customers");
            // オプションを有効化 ↓この行を追加(必要なものだけでOK)
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); 
            // 
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: null,
                model: builder.GetEdmModel());

        }
    }

各オプションはSystem.Web.OData.Extensions.HttpConfigurationExtensionsで定義されている。

Contoller側の設定

GetメソッドにEnebleQuery属性を追加し、許可したいクエリオプションをAllowedQueryOptionsで指定。
各オプションは「|」で結合

Contoller
        [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Count | AllowedQueryOptions.Skip)]
        public IQueryable<Customer> Get()
        {
            return db.Customer;
        }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1