Skip to main content
 首页 » 编程设计

c#之用于过滤的 Web API 动态参数

2024年02月05日26itcoder

我正在使用 Web API 构建 API,其中我将数据库表作为 JSON 返回。

这是我的 Controller 方法:

public List<ExampleDataDTO> ExampleData(int offset = 0, int limit = 0) 
{ 
    return DataAccessLayer.GetExampleData(offset, limit); 
} 

数据访问方法:

public List<ExampleDataDTO> GetExampleData(int offset, int limit) 
        { 
            using (var db = new Context()) 
            { 
                db.Configuration.ProxyCreationEnabled = false; 
                var exampleQuery = db.example.AsEnumerable().Select(item => 
                 new ExampleDataDTO 
                 { 
                    //Selects 
                 }); 
 
                if(offset == 0 && limit == 0) 
                { 
                    return exampleQuery .ToList(); 
                } 
                else 
                { 
                    return exampleQuery .Skip(offset).Take(limit).ToList(); 
                } 
            } 
        } 

现在 ExampleDataDTO 包含 100 多个文件,我希望能够使用 API 过滤任何字段的数据。

有没有办法制作动态查询参数?例如,如果我去 localhost/api/ExampleData?offset=0&limit=10&name=test1&size=test2我想获取名称和大小的键和值,以便能够将它们包含在我的 LINQ 代码中。

这可行吗?

编辑:

我可以得到所有的参数 IEnumerable<KeyValuePair<String, String>> queryString

有什么方法可以在 lambda 表达式中使用 Key 来遍历所有 keyValuePairs 吗?比如哪里(c = c.Key == Value),

foreach(var queryKeyValuePair in queryString) 
{ 
    Something including Where(c => c.queryKeyValuePair.Key == queryKeyValuePair.Value) 
} 

请您参考如下方法:

您可以使用 OData使用 WebAPI Controller 动态应用:filter、orderby、select、skip、top(take)。

例如:

// your API action 
public IQueryable<ExampleDataDTO> Get(ODataQueryOptions opts) 
{ 
    // here is some odata settings to validate query params. 
    var settings = new ODataValidationSettings() 
    { 
        // Initialize settings as needed. 
        AllowedFunctions = AllowedFunctions.AllMathFunctions 
    }; 
 
    // validating parameters 
    opts.Validate(settings); 
 
    var yourExampleQuery = // some data from db 
 
    // apply all parameters that came within query to your data 
    IQueryable results = opts.ApplyTo(yourExampleQuery.AsQueryable()); 
 
    // and return this 
    return results as IQueryable<Product>; 
} 

您的查询可能类似于:http://localhost/ExampleData?$filter=SomeProperty eq 'SomeValue' $orderby=anotherProperty & $skip=10 & $top=10

所有查询参数都将被解析为 ODataQueryOptions 并应用于您的 API 调用结果。

希望对您有所帮助。