ASP. NET Web API Model-ValueProvider,

Source: Internet
Author: User

ASP. NET Web API Model-ValueProvider,
ASP. NET Web API Model-ValueProvider Preface

The previous article explains Model metadata. Model metadata is an important part of Model binding. It only involves a lot of knowledge points in Model binding. for ASP. net mvc Framework ASP. in the "Model binding" section of the NET Web API framework, a parameter binding mechanism is added, which will be described later, the previous sections explain theoretical knowledge and do not involve demonstration of examples. You don't have to worry about connecting all the previous sections after the basic knowledge of the last Model, today, this article will bring you a crucial link in Model binding. You don't have to worry about Model binding, instead, we simply understand the ValueProvider series of object models, because we do not know where the ValueProvider is executed until it is combined with the knowledge points. So let's take a closer look at the ValueProvider-related objects.

 

Model-ValueProvider

Figure 1

 

IValueProviderInterface Type-- ValueProviderBehavior constraints

First, let's take a look at the right part of Section 1. The header is an IValueProvider interface type. Let's take a look at the interface definition:

Sample Code 1-1

    public interface IValueProvider    {        bool ContainsPrefix(string prefix);        ValueProviderResult GetValue(string key);    }

We can see in code 1-1 that the IValueProvider interface defines two methods. One is the ContainsPrefix () method, which receives parameters of the string type and returns the bool value type, this method is used to check whether this prefix value exists in the current ValueProvider Based on the specified prefix value. The following example will be used later, followed by the GetValue () method, returns the corresponding value based on the executed key value. From this point of view, we can probably guess that this ValueProvider should be of the same type as the key value team, the returned results are encapsulated in the ValueProviderResult type, which will be described later. After the IValueProvider interface limits the behavior of the ValueProvider value provider, let's take a look at the basic structure of the ValueProvider value provider. But before that, we still need to take a look at the definition of the IEnumerableValueProvider interface type as shown in Figure 1. What is the main responsibility of this interface?

 

IEnumerableValueProviderInterface Type-ValueProviderBehavior constraints

Sample Code 1-2

    public interface IEnumerableValueProvider : IValueProvider    {        IDictionary<string, string> GetKeysFromPrefix(string prefix);    }

From code 1-2, we can clearly see that the role of the IEnumerableValueProvider interface type is very simple, that is, to retrieve the specified prefix value and finally return it as a key-value team, this example is described in detail below.

 

NameValuePairsValueProviderType-ValueProviderInfrastructure

Sample Code 1-3

    public class NameValuePairsValueProvider : IEnumerableValueProvider, IValueProvider    {        public NameValuePairsValueProvider(Func<IEnumerable<KeyValuePair<string, string>>> valuesFactory, CultureInfo culture);        public NameValuePairsValueProvider(IEnumerable<KeyValuePair<string, string>> values, CultureInfo culture);        public virtual bool ContainsPrefix(string prefix);        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix);        public virtual ValueProviderResult GetValue(string key);    }

In code 1-3, we can see the definition of the NameValuePairsValueProvider type. Let's talk about its constructor. The difference between the two constructor is that the first one is Func <IEnumerable <KeyValuePair <string, string >>> Type constructor parameter, and the second is IEnumerable <KeyValuePair <string, string> Type constructor parameter, the first parameter type of the second constructor is actually the return type of the first parameter of the first constructor. As you can see here, it is actually implemented internally, this is also the case where it is okay to declare the first constructor. When declaring the Second constructor, the parameter is actually encapsulated as a delegate again.

For the KeyValuePair <T, U> type, it can be understood as a subitem of the key-value team. In its type, only one key value corresponds to one value and only one key value is itself.

As for the remaining three methods, let's use a simple example to illustrate them.

Sample Code 1-4

Public class ValueProviderCaseController: ApiController {public string Get () {KeyValuePair <string, string> [] dictionary = new KeyValuePair <string, string> [] {new KeyValuePair <string, string> ("EmployeesInfo. name "," Jinyuan "), new KeyValuePair <string, string> (" EmployeesInfo. age "," 24 "), new KeyValuePair <string, string> (" EmployeesInfo. sex "," male "), new KeyValuePair <string, string> (" EmployeesInfo. addressInfo. ad DressInfo "," Nanjing "), new KeyValuePair <string, string> (" EmployeesInfo. addressInfo. zipCode "," 210000 ")}; region identifier = new NameValuePairsValueProvider (dictionary, null); StringBuilder strBuilder = new StringBuilder (); NameValuePairsPrefixAnalysis (strBuilder, struct," EmployeesInfo "); return strBuilder. toString ();} private void NameValuePair SPrefixAnalysis (StringBuilder stringbuilder, NameValuePairsValueProvider namevaluepairs, string prefix) {IDictionary <string, string> dictionarys = namevaluepairs. getKeysFromPrefix (prefix); if (dictionarys. count> 0) {Console. writeLine (prefix + "data source Key value retrieval with the prefix ...... "); Foreach (var item in dictionarys) {Console. writeLine ("Key:" + item. key + "Value:" + item. value);} foreach (KeyValuePair <string, string> keyvalue in dictionarys) {NameValuePairsPrefixAnalysis (stringbuilder, namevaluepairs, keyvalue. value) ;}} else {stringbuilder. appendLine (prefix + ":" + namevaluepairs. getValue (prefix ). rawValue. toString ());}}}

Let's take a look at code 1-4. First, I defined a KeyValuePair <string, string> [] type in the Get () method. to instantiate the NameValuePairsValueProvider type, after that, you can see that I have called a custom NameValuePairsPrefixAnalysis () method, and the GetKeysFromPrefix () method is called by using an instance of the NameValuePairsValueProvider type, that is, the behavior restricted by code 1-2. At this time, let's first look at table 1.

 

Table 1

Key

Value

EmployeesInfo. Name

Jinyuan

EmployeesInfo. Age

24

EmployeesInfo. Sex

Male

EmployeesInfo. AddressInfo. AddressInfo

Nanjing

EmployeesInfo. AddressInfo. ZipCode

210000

Table 1 represents the initial data source, that is, the KeyValuePair <string, string> [] type key and value table.

However, the IDictionary <string, string> type values returned after the GetKeysFromPrefix () method is called using an instance of the NameValuePairsValueProvider type "EmployeesInfo" as the prefix, as shown in table 2.

 

Table 2

Key

Value

Name

EmployeesInfo. Name

Age

EmployeesInfo. Age

Sex

EmployeesInfo. Sex

AddressInfo

EmployeesInfo. AddressInfo

The value of Table 2 here is only the Relational Value of the first layer.

After that, we output the current prefix Value to be retrieved and the retrieved Value, and traverse the Value in Table 2 as the prefix Value to re-search the data source for the prefix, if no, it indicates that no search is available.

The GetValue () method called by an instance of NameValuePairsValueProvider type cannot be found based on the suffix prefix value, that is, the Key value in the original data source.

Finally, let's take a look at the results.

Figure 2

We obtained the value from the client. Of course, this is just a demo. The value direction provided by the value provider is reversed.

Then we can see the retrieved records on the server, and we can clearly see that there are two layers of structure in it. If you are interested, take a closer look at the specific implementation of the search.

 

QueryStringValueProviderType-ValueProviderSpecific Structure

Sample Code 1-5

    public class QueryStringValueProvider : NameValuePairsValueProvider    {        public QueryStringValueProvider(HttpActionContext actionContext, CultureInfo culture)            : base(func, culture)        {            Func<IEnumerable<KeyValuePair<string, string>>> func = null;            if (func == null)            {                func = () => actionContext.ControllerContext.Request.GetQueryNameValuePairs();            }        }    }

From code 1-5, we can see the execution of the constructor during the initialization of the QueryStringValueProvider type, encapsulate the request query string as the original data source as the delegate type, and then call the constructor of the base class.

 

RouteDataValueProviderType-ValueProviderSpecific Structure

Sample Code 1-6

    public class RouteDataValueProvider : NameValuePairsValueProvider    {        public RouteDataValueProvider(HttpActionContext actionContext, CultureInfo culture)            : base(func, culture)        {            Func<IEnumerable<KeyValuePair<string, string>>> func = null;            if (func == null)            {                func = () => GetRoutes(actionContext.ControllerContext.RouteData);            }        }    }

In the same way as 1-5 above, the Values value in HttpRouteData is used as the original data source.

The left part of Figure 1 will be explained in the subsequent sections. It is not suitable and will be incoherent, although I do not know what role this plays or how to use it after reading this article, I feel as uncomfortable as being shackled by my neck, however, in the future, I will concatenate all the content mentioned above for a demonstration. This is the basic knowledge and a foreshadowing.

 

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.


WEB APIs are different from web mvc APIs.

WebAPI is added to the new MVC to provide a REST-style WebService. The new WebAPI project is the same as the typical MVC project, including the main Models, Views, Controllers and other folders and Global. asax file. Views is not very useful for webapis. The Model in Models is mainly used to save the objects for interaction between the Service and the Client. By default, these objects are converted to Json format for data transmission in two rows, the Controller in Controllers is a Resource corresponding to WebService and is used to provide services. Like common MVC, Global. asax is used to configure routing rules.
For a WebAPI, ingress is initially designed as the same as that of the WCF producer client and server. Currently, the ingress we haven't mentioned yet because our request is encapsulated the HTTP request rule is used to receive responses such as AJAX and Form submission.

What is a web api?

Web APIs are network application interfaces.
Today's web computing platform contains a wide range of functions, most of which can be accessed through APIS (application programming interfaces. Simplified
Single Social bookmarking service del. icio. us, to a much more complex amazon s3 'fully virtualized storage platform, think about what to do with these web APIs, it's amazing.
The web platform is classified into six basic facilities, and some related products are briefly outlined. The clue is that these products provide APIs, which means that they can be integrated by other services.
Storage Service: The Storage Service focuses on abstract and Virtualized Storage. The leader in this field is amazon s3, which has been discussed in depth in my article le in web 2.0 journal. For developers, S3 provides extremely streamlined and abstract APIs such as hash tables, allowing you to easily access information.
Another interesting service is openemy, which provides APIs similar to file system interfaces, but adds the ability to label files. Today
Earlier in the year, TechCrunch analyzed some other online storage services. But so far we have not seen the legendary disruptive storage services GDrive (from google) and LiveDrive (from Microsoft). They are likely to provide APIs.
Message Service: The concept of message service is similar to the traditional middleware. Due to technical and commercial complexity, they have not yet been developed on a large scale. In the short term, the visible web-based communication Service is Amazon Simple Queue Service. This service makes it easier for any application to communicate securely and elastically Based on queues.
Computing Service: Currently, there is no general web computing service black box that can be accessed through APIS, but many technologies point to this direction. One is alexavertical search platform, which will be mentioned in the following search Service Section. The second is grid computing, such as sungrid, datasynapse's gridserver or platform's symphony.
Encapsulating arbitrary computing tasks in APIS is a very challenging task. It may take many years for such services to become popular.
Information Service: Information Service provides massive and specific information. Including geographic data like Google Maps APIs, product data like Amazon E-Commerce and Amazon historcal Pricing Services, and the latest Yahoo! Answer's API login. What these services have in common is that they all provide
Simple APIs to access massive data may lead to unpredictable cross-application of isolated information.
Search Service: because of its basic and dominant position in the web field, search service forms a key part of the new web infrastructure. Google search
Api is a typical search abstraction mechanism earlier in the past. Another example is alexa search platform, which is designed to drive a series of vertical search engines that challenge google's position. It is quite interesting that, technically, alexa search platform is more like a computing service, but it is limited to the search field. This means the possibility of other services, such as sorting services or Data Conversion Services.
Web Service: The last broad type of Web Service is called. Its names may not be specific, but they include del. icio. us, flickr, and basecamp.
. John Musser compiled some very influential APIs in Programmableweb.
These specific services will become users of the above-mentioned services in the future, but their value is more reflected in their clear,
Specific and simple APIs to view and change your information. Although they look more like molecules than atoms, they are such basic services in today's web field, so it makes sense to regard them as components .... Remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.