本文属于 OData 系列文章
更新:
由于新版的 OData
已经默认使用了 endpoint
模式(Microsoft.AspNetCore.OData 8.0.0),不再需要额外配置,本文已经过时(asp.net core 3.1
)。
最近看 OData 的 devblog,发现他们终于支持了新版的终结点(endpoint )模式路由了,于是我就迫不及待地试了试。
现在的 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();
}
总之就是对强迫症非常不友好。
终于,从 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 模式之间反复横跳了,治愈了我的强迫症。