我有一些动态查询字符串参数,我想与IDictionary< string,string>进行交互。我该如何做?
我试过了
public IHttpActionResult Get(FromUri]IDictionary<string,string> selections)
/api/MyController?selections%5Bsub-category%5D=kellogs
它总是给我一个有0个项目的字典。
我甚至不需要选择前缀。我真的只需要所有的querystring参数作为字典。我该怎么做,为什么上述不行?
解决方法
您可以使用HttpRequestMessage上的
GetQueryNameValuePairs
extension method获取解析的查询字符串作为键值对的集合。
public IHttpActionResult Get() { var queryString = this.Request.GetQueryNameValuePairs(); }
并且您可以创建一些其他的扩展方法,以使eaiser能够如下所述进行操作:WebAPI: Getting Headers,QueryString and Cookie Values
/// <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); } }