In the previous article, asp.net mvc source code analysis-Action IModelBinder, we mentioned ValueProvider. In fact, this is the property of the Controller. in the previous article, the Controller was intended to write a book about it, later, I will write the relevant stuff for later use, so that the demand can promote development. It is very important to describe this attribute stone. The value of the Action parameter is always obtained through it.
Public IValueProvider ValueProvider {
Get {
If (_ valueProvider = null ){
_ ValueProvider = ValueProviderFactories. Factories. GetValueProvider (ControllerContext );
}
Return _ valueProvider;
}
Set {
_ ValueProvider = value;
}
}
Let's see what the ValueProviderFactories class is.
Public static class ValueProviderFactories {
Private static readonly ValueProviderFactoryCollection _ factories = new ValueProviderFactoryCollection (){
New ChildActionValueProviderFactory (),
New FormValueProviderFactory (),
New JsonValueProviderFactory (),
New RouteDataValueProviderFactory (),
New QueryStringValueProviderFactory (),
New HttpFileCollectionValueProviderFactory (),
};
Public static ValueProviderFactoryCollection Factories {
Get {
Return _ factories;
}
}
}
It seems that we have added 6 ProviderFactory by default. This order is very important.
Public IValueProvider GetValueProvider (ControllerContext controllerContext ){
Var valueProviders = from factory in _ serviceResolver. Current
Let valueProvider = factory. GetValueProvider (controllerContext)
Where valueProvider! = Null
Select valueProvider;
Return new ValueProviderCollection (valueProviders. ToList ());
}
GetValueProvider returns a ValueProvider collection class ValueProviderCollection, so I think this method name should be added with s to GetValueProviders. Here _ serviceResolver. Current is the default six ProviderFactory.
Except for JsonValueProviderFactory, valueProvider can be returned only when controllerContext is valid. Their valueProvider types correspond to the following in sequence:
ChildActionValueProviderFactory-> ChildActionValueProvider
FormValueProviderFactory-> FormValueProvider
RouteDataValueProviderFactory-> RouteDataValueProvider
QueryStringValueProviderFactory-> QueryStringValueProvider
HttpFileCollectionValueProviderFactory-> HttpFileCollectionValueProvider
In addition to verifying whether the controllerContext data is valid, JsonValueProviderFactory also needs to verify whether the json format is correct. Therefore, it directly returns a class DictionaryValueProvider <object>.
We don't need to worry about every ValueProvider instance class here. It's too detailed.
Now we can get a ValueProviderCollection, which has a very useful method.
Public virtual ValueProviderResult GetValue (string key ){
Return GetValue (key, skipValidation: false );
}
Public virtual ValueProviderResult GetValue (string key, bool skipValidation ){
Return (from provider in this
Let result = GetValueFromProvider (provider, key, skipValidation)
Where result! = Null
Select result). FirstOrDefault ();
}
From the previously obtained ValueProvider, their GetValue method will be used to return a ValueProviderResult set without ValueProviderResult being null, and the first ValueProviderResult in the set will be returned at most.
Internal static ValueProviderResult GetValueFromProvider (IValueProvider provider, string key, bool skipValidation ){
// Since IUnvalidatedValueProvider is a superset of IValueProvider, it's always OK to use
// IUnvalidatedValueProvider-supplied members if they're present. Otherwise just call
// Normal IValueProvider members.
IUnvalidatedValueProvider unvalidatedProvider = provider as IUnvalidatedValueProvider;
Return (unvalidatedProvider! = Null )? UnvalidatedProvider. GetValue (key, skipValidation): provider. GetValue (key );
}
Why is the above Code such as provider as IUnvalidatedValueProvider? Because
QueryStringValueProvider and NameValueCollectionValueProvider both inherit from NameValueCollectionValueProvider
Public class NameValueCollectionValueProvider: IValueProvider, IUnvalidatedValueProvider
However, ChildActionValueProvider, RouteDataValueProvider, and HttpFileCollectionValueProvider inherit from DictionaryValueProvider.
Public class DictionaryValueProvider <TValue>: IValueProvider
The main method of NameValueCollectionValueProvider is as follows:
private void AddValues(NameValueCollection validatedCollection, NameValueCollection unvalidatedCollection, CultureInfo culture) { // Need to read keys from the unvalidated collection, as M.W.I's granular request validation is a bit touchy // and validated entries at the time the key or value is looked at. For example, GetKey() will throw if the // value fails request validation, even though the value's not being looked at (M.W.I can't tell the difference). if (unvalidatedCollection.Count > 0) { _prefixes.Add(""); } foreach (string key in unvalidatedCollection) { if (key != null) { _prefixes.UnionWith(ValueProviderUtil.GetPrefixes(key)); // need to look up values lazily, as eagerly looking at the collection might trigger validation _values[key] = new ValueProviderResultPlaceholder(key, validatedCollection, unvalidatedCollection, culture); } } } public virtual ValueProviderResult GetValue(string key, bool skipValidation) { if (key == null) { throw new ArgumentNullException("key"); } ValueProviderResultPlaceholder placeholder; _values.TryGetValue(key, out placeholder); if (placeholder == null) { return null; } else { return (skipValidation) ? placeholder.UnvalidatedResult : placeholder.ValidatedResult; } }
The main method of DictionaryValueProvider is as follows:
private void AddValues(IDictionary<string, TValue> dictionary, CultureInfo culture) { if (dictionary.Count > 0) { _prefixes.Add(""); } foreach (var entry in dictionary) { _prefixes.UnionWith(ValueProviderUtil.GetPrefixes(entry.Key)); object rawValue = entry.Value; string attemptedValue = Convert.ToString(rawValue, culture); _values[entry.Key] = new ValueProviderResult(rawValue, attemptedValue, culture); } } public virtual ValueProviderResult GetValue(string key) { if (key == null) { throw new ArgumentNullException("key"); } ValueProviderResult vpResult; _values.TryGetValue(key, out vpResult); return vpResult; }
Here, we can see that ValueProviderResultPlaceholder is a packaging class of ValueProviderResult, which enables delayed loading of its data,
private sealed class ValueProviderResultPlaceholder { private readonly Lazy<ValueProviderResult> _validatedResultPlaceholder; private readonly Lazy<ValueProviderResult> _unvalidatedResultPlaceholder; public ValueProviderResultPlaceholder(string key, NameValueCollection validatedCollection, NameValueCollection unvalidatedCollection, CultureInfo culture) { _validatedResultPlaceholder = new Lazy<ValueProviderResult>(() => GetResultFromCollection(key, validatedCollection, culture), LazyThreadSafetyMode.None); _unvalidatedResultPlaceholder = new Lazy<ValueProviderResult>(() => GetResultFromCollection(key, unvalidatedCollection, culture), LazyThreadSafetyMode.None); } private static ValueProviderResult GetResultFromCollection(string key, NameValueCollection collection, CultureInfo culture) { string[] rawValue = collection.GetValues(key); string attemptedValue = collection[key]; return new ValueProviderResult(rawValue, attemptedValue, culture); } public ValueProviderResult ValidatedResult { get { return _validatedResultPlaceholder.Value; } } public ValueProviderResult UnvalidatedResult { get { return _unvalidatedResultPlaceholder.Value; } } }
I will not mention other details. In projects, we often need to implement our own ValueProviderFactory, so we need to register it and Add ValueProviderFactories. Factories. Add (xxxx) in Application_Start ).
Let's take a demo to illustrate how to use it.
Public class rule: ValueProviderFactory {public rule () {} public override IValueProvider GetValueProvider (ControllerContext controllerContext) {if (controllerContext = null) {throw new rule ("controllerContext ");} return new CookieValueProvider (controllerContext) ;}} public class CookieValueProvider: NameValueCollectionValueProvider {public CookieValueProvider (ControllerContext controllerContext): base (GetCookies (controllerContext), CultureInfo. invariantCulture) {} static NameValueCollection GetCookies (ControllerContext controllerContext) {NameValueCollection data = new NameValueCollection (); foreach (string key in controllerContext. httpContext. request. cookies. allKeys) {data. add (key, controllerContext. httpContext. request. cookies [key]. value);} return data;} public class HomeController: Controller {public ActionResult Index (string name) {if (string. isNullOrEmpty (name) {Response. cookies. add (new HttpCookie ("name", "majiang"); return Content ("Write cookie");} else {return Content ("read cookie: "+ name );}}}
Add ValueProviderFactories. Factories. Add (new CookieValueProviderFactory () to Application_Start ());
Two running results