作为属性路由的新手,我想请求帮助让它工作。
此测试是一个简单的动态数据库表查看器:给定一个表名(或存储的查询名称或其他)以及可选的一些WHERE参数,返回查询结果。
表公司(任意数量的表之一,其中存储了关联的SELECT查询,按表名键控):
ID NAME HQ INDUSTRY
1 Apple USA Consumer electronics
2 Bose USA Low-quality, expensive audio equipment
3 Nokia FIN Mobile Phones
控制器:
[Route("view/{table}/{parameters}")]
public object Get(string table, Dictionary<string, string> parameters) {
var sql = GetSql(table);
var dbArgs = new DynamicParameters(parameters);
return Database.Query(sql, dbArgs); // Return stuff/unrelated to problem
}
SQL存储在某些资源或表中。显然,参数必须完全匹配:
SELECT * FROM companies
WHERE name = :name
-- OR hq = :hq
-- OR ...etc. Doesn't matter since it never gets this far.
请求(应该看起来干净,但确切的URL格式并不重要):
www.website.com/view/companies?hq=fin
- > 404:没有匹配的控制器www.website.com/view/companies/hq=fin
- > parameters
为null www.website.com/view/companies/hq=fin&name=nokia
- >异常: A potentially dangerous Request.Path value was detected from the client (&).
当我使用: [Route("view/{table}{parameters}")]
我得到:
A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by a literal string. Parameter name: routeTemplate
。说得通。
我的问题是:我如何接受通常的key1=val1&key2=val2
形式的表名和 任意数量的未知参数 ( 不是像这里提到的那样的一些笨拙的索引格式),后来将绑定到SQL参数,最好使用vanilla数据结构而不是FormCollection
。
我不认为绑定到字典的URL参数是内置于框架。如果你愿意的话,我确定有办法扩展它。
我认为最快(但仍然可以接受)选项是使用Request.GetQueryNameValuePairs()
获取查询字符串参数,如下所示:
[Route("view/{table}")]
public object Get(string table) {
Dictionary<string, string> parameters = Request.GetQueryNameValuePairs()
.ToDictionary(x => x.Key, x => x.Value);
var sql = GetSql(table);
var dbArgs = new DynamicParameters(parameters);
return Database.Query(sql, dbArgs); // Return stuff/unrelated to problem
}