Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

asp.net web api - How to access all querystring parameters as a dictionary

I have some dynamic querystring parameters that I would like to interact with as an IDictionary<string,string>. How do I do this?

I tried

public IHttpActionResult Get(FromUri]IDictionary<string, string> selections)

as suggested but for a query of

/api/MyController?selections%5Bsub-category%5D=kellogs

it always gives me a dictionary with 0 items.

I don't even need the selections prefix. I literally just need all querystring parameters as a dictionary. How do I do this and why won't the above work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the GetQueryNameValuePairs extension method on the HttpRequestMessage to get the parsed query string as a collection of key-value pairs.

public IHttpActionResult Get()
{
    var queryString = this.Request.GetQueryNameValuePairs();
}

And you can create some further extension methods to make it eaiser to work with as described here: 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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...