Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Adding common extension methods and thinking divergence to WebAPi

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

WebAPi commonly used extension method (1) to get all key-value pairs

/ public static Dictionary GetQueryStrings (this HttpRequestMessage request) {return request.GetQueryNameValuePairs () .ToDictionary (k = > k.Key, v = > v.Value, StringComparer.OrdinalIgnoreCase);}

(2) obtain the corresponding value of a single key

/ get a single key value / public static string GetQueryString (this HttpRequestMessage request, string key) {var queryStrings = request.GetQueryNameValuePairs (); if (queryStrings = = null) return null Var match = queryStrings.FirstOrDefault (kv = > string.Compare (kv.Key, key, true) = = 0); if (string.IsNullOrEmpty (match.Value)) return null; return match.Value;}

Note: please don't tell me to use HttpContext.Current.Request.QueryString ["key"] to get the key value, it's OK in WebHost mode, but the object is empty in SelfHost mode.

(3) obtain the corresponding key value in the request header

/ obtain the request header median data according to the key / public static string GetHeader (this HttpRequestMessage request, string key) {IEnumerable keys = null; if (! request.Headers.TryGetValues (key, out keys)) return null; return keys.First () }

(4) obtain the key value in Cookie

/ get Cookie / public static string GetCookie (this HttpRequestMessage request, string cookieName) {CookieHeaderValue cookie = request.Headers.GetCookies (cookieName). FirstOrDefault (); if (cookie! = null) return cookie [cookiename] .value; return null;}

Thinking divergence

We know that QueryString is used when getting request parameter values in ASP.NET, NameValueCollection is sometimes used when getting the median value of Web.config configuration, and request headers. In the above we return Dictionary, so what is the difference between Dictionary and NameValueCollection when getting parameters?

NameValueCollection

Let's take a look at its specific usage, add the corresponding data to this class and get:

Static NameValueCollection GetCollection () {var collection = new NameValueCollection (); collection.Add ("Zhang San", "blog Garden"); collection.Add ("Li Si", "csdn"); collection.Add ("Li Si", "51cto"); collection.Add ("Zhang San", "IBM"); return collection;}

Print:

Var collection = GetCollection (); foreach (string key in collection.AllKeys) {Console.WriteLine (key); Console.WriteLine (replacement [key]);}

As can be seen from above, the key at this time is not returned repeatedly, but at this time each key is mapped to a string array, that is, the value corresponding to the same key is stored in it. So we can conclude that when traversing the NameValueCollection collection through the AllKeys property, the keys returned at this time are all unrepeated keys.

What happens if we take a key that doesn't exist?

Console.WriteLine (collection ["xpy0928"] = = null)

The True will print out.

Based on this, we can draw a conclusion:

When fetching values by key in the NameValueCollection collection, if more than one value is found, a comma-separated array of strings is returned, or empty if not found.

Next, let's look at other methods for this collection:

Console.WriteLine (collection.HasKeys ()); Console.WriteLine (collection.GetKey (0)); string value = collection.Get (0); Console.WriteLine (value)

(1) the first to show whether a key exists in the collection (returns True).

(2) get the first key of the collection (return Zhang San).

(3) get the value corresponding to the first key (return to blog Park, IBM).

The above is all about judging the key and fetching the key value, of course, there are methods to add and remove, add us needless to say, let's look at the removal method.

Collection.Remove ("Zhang San"); collection.Remove ("xpy0928"); foreach (var key in collection.AllKeys) {Console.WriteLine (key); Console.WriteLine (alternative [key]);}

When you remove an existing key, all values corresponding to that key are deleted, but interestingly, removing a non-existent key does not throw an exception at all.

Dictionary

Next let's take a look at Dictionary.

Static Dictionary GetDict () {var dictionary = new Dictionary (); dictionary.Add ("Zhang San", "blog Garden"); dictionary.Add ("Li Si", "csdn"); dictionary.Add ("Wang Wu", "51cto"); dictionary.Add ("Zhao Liu", "IBM"); return dictionary;}

Let's add an item to see

Var dict = GetDict (); dict.Add ("Zhang San", "blog Garden")

You cannot add duplicates to the dictionary.

At this point, we can conclude that the main difference between NameValueCollection and Dictionary is that NameValueCollection can add duplicates, but Dictionary can't.

Of course, removing non-existent keys from the dictionary will not throw an exception, as follows:

Dict.Remove ("xpy928")

Next, let's see if there is a performance difference between the two when looking up data, which we do in Release mode.

Var collection = GetCollection (); var dict = GetDict (); var stopWatch = new Stopwatch (); stopWatch.Start (); for (int I = 0; I < 100000000; iTunes +) {string value = collection ["Zhang San"];} var time = stopWatch.ElapsedMilliseconds; Console.WriteLine (time) StopWatch.Stop (); var stopWatchDict = new Stopwatch (); stopWatchDict.Start (); for (int I = 0; I < 100000000; iTunes +) {string value = dict ["Zhang San"];} var time1 = stopWatchDict.ElapsedMilliseconds; Console.WriteLine (time1); stopWatchDict.Stop ()

As above, let's iterate 1 billion times to see if there is any performance difference in finding data:

Here we can see that it takes 48 seconds to get data with NameValueCollection and 4 seconds with Dictionary, which shows that there are great differences in performance between the two in addition to adding data and iterating query data.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report