我想从应用程序设置文件中获取页面大小值并在控制器属性上使用它
[EnableQuery(PageSize = 5)]
而不是硬编码。
public class PersonController : ODataController
{
public string pageSize;
public PersonController(IPersonService personService, IOptions<Configurations> configurations, ILoggingService loggingService)
{
_personService = personService;
_configurations = configurations.Value;
_loggingService = loggingService;
pageSize = _configurations.PageSize;
}
[HttpGet("/persons/")]
//[EnableQuery(PageSize = 5)] Works
[EnableQuery(PageSize = pageSize)] // Doesn't work
public ActionResult<IEnumerable<person>> Get()
{
}
}
通过评论部分的讨论,我们可以在方法中访问 _configurations.PageSize。
选项 1(如果可能):
public ActionResult<IEnumerable<person>> Get(ODataQueryOptions<person> options)
{
int pageSize = int.Parse(_configurations.PageSize);
options.Top = pageSize;
var personsquery = Get the data from your service with Queryable
var result = options.ApplyTo(personsquery);
return Ok(result);
}
选项 2 自定义属性:
//This is new new attribute so place this code under appropriate folder in your //application
public class PageSizeFromConfigAttribute : EnableQueryAttribute
{
public PageSizeFromConfigAttribute(string appsettingskey)
{
var pageSize = GetPageSizeFromConfig(appsettingskey);
PageSize = pageSize;
}
private int GetPageSizeFromConfig(string appsettingskey)
{
return int.Parse(_configurations[appsettingskey]);
}
}
[HttpGet("/persons/")]
//[EnableQuery(PageSize = 5)] Works
//[EnableQuery(PageSize = pageSize)] // Doesn't work
[PageSizeFromConfig(nameof(Configurations.PageSize))] //try this
public ActionResult<IEnumerable<person>> Get()
{
}