武裝你的WEBAPI-OData使用Endpoint

本文屬於 OData 系列文章

Introduction

更新:
由於新版的 OData 已經默認使用了 endpoint 模式(Microsoft.AspNetCore.OData 8.0.0),不再需要額外配置,本文已經過時(asp.net core 3.1)。

最近看 OData 的 devblog,發現他們終於支持了新版的終結點(endpoint )模式路由了,於是我就迫不及待地試了試。

MVC 模式

現在的 OData 配置還是需要禁用 EnableEndpointRouting,感覺和現在標準 ASP. NET CORE 套路格格不入。

public void ConfigureServices(IServiceCollection services)
{
	services.AddControllers(mvcOptions => 
		mvcOptions.EnableEndpointRouting = false);

	services.AddOData();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseHttpsRedirection();
	app.UseRouting();
	app.UseAuthorization();

	app.UseMvc(routeBuilder =>
	{
		routeBuilder.Select().Filter();
		routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
	});

	//app.UseEndpoints(endpoints =>
	//{
	//    endpoints.MapControllers();
	//});
}

IEdmModel GetEdmModel()
{
	var odataBuilder = new ODataConventionModelBuilder();
	odataBuilder.EntitySet<Student>("Students");

	return odataBuilder.GetEdmModel();
}

總之就是對強迫症非常不友好。

Endpoint 模式

終於,從 7.4 開始支持默認的 ASP. NET CORE Endpoint 模式了,你需要安裝 7.4 的 odata 包:

Install-Package Microsoft.AspNetCore.OData -Version 7.4.0-beta

配置代碼如下:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddOData();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.Select().Filter().OrderBy().Count().MaxTop(10);
                endpoints.MapODataRoute("odata", "odata", GetEdmModel());
            });
        }

        private IEdmModel GetEdmModel()
        {
            var odataBuilder = new ODataConventionModelBuilder();
            odataBuilder.EntitySet<WeatherForecast>("WeatherForecast");

            return odataBuilder.GetEdmModel();
        }
    }

後面就不用在 MVC 模式與 Endpoint 模式之間反覆橫跳了,治癒了我的強迫症。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章