属性路由不与字典一起使用

时间:2013-12-30 23:40:17

标签: asp.net-web-api dapper attributerouting asp.net-web-api2

作为属性路由的新手,我想请求帮助让它工作。

此测试是一个简单的动态数据库表查看器:给定一个表名(或存储的查询名称或其他)以及可选的一些WHERE参数,返回查询结果。

Table COMPANIES(任意数量的表之一,其中存储了关联的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 - &gt; 404:没有匹配的控制器 www.website.com/view/companies/hq=fin - &gt; parameters为空 www.website.com/view/companies/hq=fin&name=nokia - &gt; 例外: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表单(一些笨拙的索引格式,如提到的here),后来将绑定到SQL参数,最好使用vanilla数据结构,而不是类似{ {1}}。

1 个答案:

答案 0 :(得分:2)

我认为绑定到字典的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
}