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

Take Page Size Value from Config file in EnableQuery Attribute

提问人:Dave 提问时间:11/12/2023 最后编辑:marc_sDave 更新时间:11/15/2023 访问量:35

问:

我想从应用程序设置文件中获取页面大小值,并在控制器属性上使用它,而不是硬编码。[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 控制器 OData

评论

0赞 Rajesh P 11/12/2023
尝试使用 [EnableQuery(PageSize = _configurations.PageSize)],你见过那个_configurations吗?构造函数中的 PageSize 是否从您添加的配置中获取值?
0赞 Dave 11/12/2023
@RajeshP 它不起作用。
0赞 Rajesh P 11/12/2023
你能_configurations得到这个值吗?构造函数中的 PageSize ?
0赞 Dave 11/12/2023
@RajeshP是的,我可以看到我在应用程序设置中设置的值。
0赞 Rajesh P 11/12/2023
好的,这里我们有两种选择来满足您的要求

答:

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)