从配置文件中的EnableQuery属性中获取页面大小值

问题描述 投票:0回答:1

我想从应用程序设置文件中获取页面大小值并在控制器属性上使用它

[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()
     {
     }
}
c# asp.net-web-api controller odata
1个回答
0
投票

通过评论部分的讨论,我们可以在方法中访问 _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()
 {
 }
© www.soinside.com 2019 - 2024. All rights reserved.