正如本文所指出的,使用$query关键字可以解决Microsoft.AspNetCore.OData
7.5版本之后的长OData URL问题。
但在我的项目中(我使用的是版本8.preview3(,我尝试过使用这个,但我一直收到404未找到的错误。以下是我的工作URL示例:
https://localhost:44346/odata/WFC/APost/
https://localhost:44346/odata/WFC/APost/?$select=id
...
但是当我使用带有$query的POST请求时,我收到404错误:
POST: https://localhost:44346/odata/WFC/APost/$query
Content-Type: text/plain
Request Body: $select=id
我想知道是否必须添加任何代码才能启用$query功能
以下是我的相关代码:
// version 8.preview3 of Microsoft.AspNetCore.OData code
services.AddOData(
opt => opt.AddModel("odata", GetEdmModel()).Select().Count().Filter().OrderBy().SetAttributeRouting(true));
...
public IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
var s = builder.EntitySet<WeatherForecast>("WFC").EntityType;
s.Collection.Action("APost");
return builder.GetEdmModel();
}
控制器:
[ODataRoutePrefix("WFC")]
public class WeatherForecast2Controller : ODataController
{
...
[HttpPost]
[EnableQuery]
[ODataRoute("APost")]
public IEnumerable<WeatherForecast> APost()
{
// this function just returns array of 10 WeatherForecast(s) .
...
}
}
您不必创建POST端点。POST.../$query
请求应该转换为GET端点。
但是,您需要使用中间件:
// Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseODataQueryRequest();
}
有关更多信息,请参阅https://github.com/OData/WebApi/issues/2414#issuecomment-1021571407.