我有一些动态查询字符串参数,我想与之交互IDictionary<string,string>.我该怎么做呢?
我试过了
public IHttpActionResult Get(FromUri]IDictionary<string, string> selections)
Run Code Online (Sandbox Code Playgroud)
如建议但查询
/api/MyController?selections%5Bsub-category%5D=kellogs
Run Code Online (Sandbox Code Playgroud)
它总是给我一个0项的字典.
我甚至不需要selections前缀.我确实需要所有的查询字符串参数作为字典.我该怎么做以及为什么上述工作不顺利?
nem*_*esv 61
您可以使用GetQueryNameValuePairs扩展方法上HttpRequestMessage得到解析的查询字符串键值对的集合.
public IHttpActionResult Get()
{
var queryString = this.Request.GetQueryNameValuePairs();
}
Run Code Online (Sandbox Code Playgroud)
您可以创建一些进一步的扩展方法,使其可以使用,如下所述:WebAPI:获取标题,QueryString和Cookie值
/// <summary>
/// Extends the HttpRequestMessage collection
/// </summary>
public static class HttpRequestMessageExtensions
{
/// <summary>
/// Returns a dictionary of QueryStrings that's easier to work with
/// than GetQueryNameValuePairs KevValuePairs collection.
///
/// If you need to pull a few single values use GetQueryString instead.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static Dictionary<string, string> GetQueryStrings(
this HttpRequestMessage request)
{
return request.GetQueryNameValuePairs()
.ToDictionary(kv => kv.Key, kv=> kv.Value,
StringComparer.OrdinalIgnoreCase);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42314 次 |
| 最近记录: |