【发布时间】:2021-04-09 13:49:56
【问题描述】:
注意:这不是重复的,因为我在AspNetCore 中使用的是全新的OData 实现版本。
基于 Microsoft 的 this 文章,我尝试使用 AttributeRoutingConvetion 并最终使用 ODataRoutePrefix 和 ODataRoute 使用 Asp.net Core 5 Web API 和 Microsoft.AspNetCore.OData Version="8.0.0-preview3"(请注意 版本)。
这是我的代码:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.TryAddEnumerable(ServiceDescriptor.Transient<IODataControllerActionConvention, AttributeRoutingConvention>());
services.AddOData(
opt => opt.AddModel("odata",GetEdmModel()).Select().Count().Filter().OrderBy().SetAttributeRouting(true)
);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<WeatherForecast>("WeatherForecast2");
return builder.GetEdmModel();
}
这是我的控制器:
[ODataRoutePrefix("WFC")]
public class WeatherForecast2Controller : ODataController
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecast2Controller> _logger;
public WeatherForecast2Controller(ILogger<WeatherForecast2Controller> logger)
{
_logger = logger;
}
[HttpGet]
[EnableQuery]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
[HttpGet]
[EnableQuery]
[ODataRoute("AnotherGet")]
public IEnumerable<WeatherForecast> AnotherGet()
{
var rng = new Random();
return Enumerable.Range(1, 3).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
现在我期望调用 https://localhost:44346/WFC/AnotherGet 通过执行 AnotherGet 方法返回 3 Weatherforcast 结果,但我收到 404 错误。我也尝试了以下方法:
~/odata/WeatherForecast2 - executes Get and returns array of 5 Weatherforcast
~/odata/WFC/ - 404 not found
~/odata/WFC/AnotherGet - 404 not found
~/WFC/ - 404 not found
~/WFC/AnotherGet - 404 not found
如何执行特定的控制器及其方法?
【问题讨论】:
标签: c# asp.net-core routes odata