提问人:Dave 提问时间:11/12/2023 最后编辑:marc_sDave 更新时间:11/15/2023 访问量:35
从 EnableQuery 属性中的配置文件中获取页面大小值
Take Page Size Value from Config file in EnableQuery Attribute
问:
我想从应用程序设置文件中获取页面大小值,并在控制器属性上使用它,而不是硬编码。[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()
{
}
}
答:
0赞
Rajesh P
11/12/2023
#1
通过评论部分的讨论,我们可以访问_configurations。方法中的 PageSize。
选项 1(如果可能):
public ActionResult<IEnumerable<person>> Get(ODataQueryOptions<person> options)
{
int pageSize = int.Parse(_configurations.PageSize);
var personsquery = Get the data from your service with Queryable
var result = options.ApplyTo(personsquery,pageSize);
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()
{
}
评论
0赞
Dave
11/12/2023
在选项一选项中。顶部 = pageSize;编译器错误属性或索引器“property”无法分配给 -- 它是只读的,您是否收到相同的错误。
0赞
Rajesh P
11/15/2023
将 PageSize 发送到选项。ApplyTo(personsquery,pageSize)
评论