How to properly integrate OData with ASP.net Core

可紊 提交于 2019-12-03 04:25:30

I managed to make it work, but I didn't use the provided OData routing because I needed more granularity. With this solution, you can create your own web API, while still allowing the use of OData query parameters.

Notes:

  • I used Nuget package Microsoft.AspNetCore.OData.vNext, version 6.0.2-alpha-rtm, which requires .NET 4.6.1
  • As fas as I can tell, OData vNext only support OData v4 (so no v3)
  • OData vNext seems to have been rushed, and is packed with bugs. For example, the $orderby query parameter is broken

MyEntity.cs

namespace WebApplication1
{
    public class MyEntity
    {
        // you'll need a key 
        public int EntityID { get; set; }
        public string SomeText { get; set; }
    }
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.OData;
using Microsoft.AspNetCore.OData.Abstracts;
using Microsoft.AspNetCore.OData.Builder;
using Microsoft.AspNetCore.OData.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            /* ODATA part */
            services.AddOData();
            // the line below is used so that we the EdmModel is computed only once
            // we're not using the ODataOptions.ModelManager because it doesn't seemed plugged in
            services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel);
        }

        private static ODataModelManager DefineEdmModel(IServiceProvider services)
        {
            var modelManager = new ODataModelManager();

            // you can add all the entities you need
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<MyEntity>(nameof(MyEntity));
            builder.EntityType<MyEntity>().HasKey(ai => ai.EntityID); // the call to HasKey is mandatory
            modelManager.AddModel(nameof(WebApplication1), builder.GetEdmModel());

            return modelManager;
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Controller.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData;
using Microsoft.AspNetCore.OData.Abstracts;
using Microsoft.AspNetCore.OData.Query;
using System.Linq;

namespace WebApplication1.Controllers
{
    [Produces("application/json")]
    [Route("api/Entity")]
    public class ApiController : Controller
    {
        // note how you can use whatever endpoint
        [HttpGet("all")]
        public IQueryable<MyEntity> Get()
        {
            // plug your entities source (database or whatever)
            var entities = new[] {
                new MyEntity{ EntityID = 1, SomeText = "Test 1" },
                new MyEntity{ EntityID = 2, SomeText = "Test 2" },
                new MyEntity{ EntityID = 3, SomeText = "Another texts" },
            }.AsQueryable();

            var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger));
            var model = modelManager.GetModel(nameof(WebApplication1));
            var queryContext = new ODataQueryContext(model, typeof(MyEntity), null);
            var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request);

            return queryOptions
                .ApplyTo(entities, new ODataQuerySettings
                {
                    HandleNullPropagation = HandleNullPropagationOption.True
                })
                .Cast<MyEntity>();
        }
    }
}

How to test

You can use the following URI : /api/Entity/all?$filter=contains(SomeText,'Test'). If it works correctly, you should only see the first two entities.

Alex Buchatski

I also got Microsoft.AspNetCore.OData.vNext, version 6.0.2-alpha-rtm to work, but I used the following code to map Edm model to routes:

services.AddOData();
// ...
app.UseMvc(routes =>
{
  ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
  modelBuilder.EntitySet<Product>("Products");
  IEdmModel model = modelBuilder.GetEdmModel();
  routes.MapODataRoute(
    prefix: "odata",
      model: model
  );

along with services.AddOData()

It's strange but it seems to work with .Net Core 1.1

I have a github repo which auto generates ASP.NET Core OData v4 controllers from a code first EF model, using T4. It uses Microsoft.AspNetCore.OData.vNext 6.0.2-alpha-rtm. Might be of interest.

https://github.com/afgbeveridge/AutoODataEF.Core

Looks like this is currently in alpha with the OData team. according to this issue

From WEB API Server side:

Simplest way to use is the direct [EnableQuery] attribute. Now with recent 7.x pacakge, it is working great.

You can also easily have generic impl., as below. idea is have a common method, and disambiguate based on entity name you require. With Linq2RestANC for client side consumption, you can easily pass your custom query parameters too. As in example below, if you have 2 tables Movies1 and Movies2, then the queries will be applied directly on your db only, when you do an $expand and sub-filter/sub-process conditions within them.

[EnableQuery]
public IActionResult Get([FromQuery] string name)
{
        switch (name)
        {
            case "Movie2":
                return Ok(new List<ViewModel>{new ViewModel(Movies2=_db.Movies2)});
        }
        return Ok(new List<ViewModel>{new ViewModel(Movies1=_db.Movies1)});
 }

For client side consumption- --> Don't use ODATA Service proxy. It is buggy and throws lot of errors. --> Simple.OData.Client is good. But lags support for nested queries within expand . for eg. /Products?$expand=Suppliers($select=SupplierName;$top=1;) For such inner expand it doesn't support further filtering. That is tracked as bug #200

--> Linq2RestANC is a beautiful choice. That too natively doesn't support nested expands, but it is implemented by inheriting native IQueryProvider, so it just took 3-4 hours to modify and test the completed nested - deep level expand scenarios. You will need to change at Expressionprocessor.cs "Expand" And ParameterBuilder.cs GetFullUri() a little to get it working.

You need inherit controller from the ODataController

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!