Go ASP. NET Web API support for OData

Source: Internet
Author: User

Http://www.cnblogs.com/shanyou/archive/2013/06/11/3131583.html

In the SOA world, one of the most important concepts is the contract (contract). In the world of cloud computing, the most important concept of communication is the contract. XML has a strong ability to describe data, both atom format and atompub are built on XML, and have been standard driven by Google and Microsoft. However, compared with real data interaction protocols such as atom/atompub and Odbc/oledb, there is a fundamental deficiency: the lack of a specific description of the data type, and the reduced interaction performance. Lack of control over the data query, such as returning the interval of a particular set of data, or paging capability, etc. Microsoft releases the EDM model: OData, which also shows the different strategic considerations of the Entity Framework for ORM tools such as NHibernate.

In. NET, the early use of Remoting/webservice to handle all communication between programs, starting with the WCF Unified Communications model from. NET 3.0, and the introduction of ASP. MVC4, which forms the largest one ASP. NET strategy, adding WEBAPI and SINGALR as a communications service:

An Open Data Protocol (ODATA) is a Web protocol that queries and updates data. OData applies web technologies such as HTTP, Atom Publishing Protocol (ATOMPUB), and JSON to provide access to information for different applications, services, and storage. In addition to providing some basic operations (like adding additions and deletions), it also provides some advanced operations like filtering data and navigating entities. OData extends the above protocols but does not replace them. He can be replaced by XML (ATOM) or JSON but the importance of OData is that it conforms to the rest principle. In a sense, it is built on the ' simple ' rest HTTP service and has a clear purpose-to simplify and standardize the way we manipulate and query data. OData is a good choice if you've been having trouble creating search, filtering, or paging APIs for your rest service.

At present, many interfaces, whether based on soap, rest, or anything else, use different patterns when exchanging data. This method then returns a large pile of customer records. You can then decide to add paging support. You want to bundle the results in a grid and sort the data. Finally, decide what you want to query by, for example, a zip code.

First, there is no way to create a generic client, and these are closely related to the API because it does not know the order of the parameters or the order in which the patterns are used. Because you cannot create a generic client, you must create a client for each API that you want to expose. The simple base HTTP API can be implemented, but it is still expensive. The increasing diversity of clients communicating with these APIs exacerbates this problem.

The second problem with this pattern is that it forces developers to make very difficult tradeoffs. How many queries should I expose? You need to expose each one you can think of content and less exposure, thereby weakening the coordination between services. The former leads to an increase in the interface that the API needs to manage, which leads to what we commonly call "data silos", where critical data is locked in a particular pattern, and other applications cannot be used simply because it is not exposed to the application in a way that is needed. Services are trying to get longer than a single application, so you need to design the API in a way that will last, so if you find that you need to add a new version of the service excuse, it's not very good to do it, like creating a new client. In many cases, service developers and client developers are not the same person, so changing the service interface is simply impossible.

With OData, we take a different approach. Instead of creating client signatures and parameters, we asked the following question: "If you are processing a dataset as a source and defining patterns for the most frequently used operations, such as querying, paging, sorting, creating, deleting, and updating, what does the service interface look like?" "This also leads to the creation of OData. OData addresses the key service design challenges mentioned above.

Let's take a look at examples of WEBAPI that enable OData protocol:

Http://localhost:8080/api/meetings

Http://localhost:8080/api/meetings $filter = (Leader eq ' Mark Nichols ')

Http://localhost:8080/api/meetings? $top =2

Http://localhost:8080/api/meetings? $filter =meetingdate eq datetime ' 2013-01-17′

Enable OData queries in your project, first in the project to join the Web API's OData support, to find the ASP with NuGet Web API

Microsoft.AspNet.WebApi.OData provides a range of classes to extend the Web API.

To enable OData queries in your project:

Public static void Register (httpconfiguration config) { //... config.     Enablequerysupport (); // ... }

If you are using self-hosting mode, enable Enablequerysupport () on httpselfhostconfiguration :

var config = new httpselfhostconfiguration (new Uri ("http://localhost:8080")); config. Enablequerysupport ();

Then change the return result of the action on the controls to IQueryable and label [Queryable ()]:

        GET api/meeting        [queryable (allowedqueryoptions = allowedqueryoptions.all)] public        iqueryable< Meeting> Get ()        {            return _scheduledmeetings.asqueryable ();        } You need to add a using System.Web.Http.OData.Query; Let's look at the types of allowedqueryoptions that support those OData: 
   Summary:OData query options to allow for querying. [Flags]PublicEnum Allowedqueryoptions {Summary:A value that corresponds to allowing no query options. None = 0,//Summary:A value that corresponds to allowing the $filter query option. Filter = 1,//Summary:A value that corresponds to allowing the $expand query option. Expand = 2,//Summary:A value that corresponds to allowing the $select query option. Select = 4,//Summary:A value that corresponds to allowing the $orderby query option. = 8,//Summary:A value that corresponds to allowing the $top query option. Top = 16,//Summary://A value that corresponds to allowing the $SKIP query option. Skip = ////Summary: //A value that corresponds to allowing th E $inlinecount query option. Inlinecount = ////Summary: //A value that corresponds to the Default query options supported by System.Web.Http.QueryableAttribute. Supported = 121, ////Summary: //A value that corresponds to allow ing the $format query option. Format = $, ////Summary: //A value that corresponds to allowing The $skiptoken query option. Skiptoken = ////Summary: //A value that corresponds to allow ing all query options. All = 511,}               

It has a format, and we can do the formatting output. Use the following code to format format data:

Class Webapiconfig    {        

Config. Formatters.JsonFormatter.AddQueryStringMapping ("$format", "JSON", "Application/json"); config. Formatters.XmlFormatter.AddQueryStringMapping ("$format", "xml", " application/xml");

            Config. Enablequerysupport ();        }

It is also important to note that OData queries are case-sensitive.

I'm going to use fiddler to test this service.

We have not written any particular logic to support these functions, all of which are provided by the framework. Whether OData provides a good option for your search, filtering, or paging API.

However, if you want to expose queryable operations outside your organization, you can use query validation to add a layer of protection to protect our services. Microsoft's Program Manager Hongmei GE introduced several scenarios for adding validation to the Queryable API.

The first scenario Hongmei points out is that, using the Allowedqueryoptions property, only queries that contain $top and $skip are allowed. As shown below:

[Queryable (allowedqueryoptions = Allowedqueryoptions.skip | Allowedqueryoptions.top)] public IQueryable Get (int projectid)

You can also use the Maxtop and Maxskip properties to limit the maximum values of $top and $skip to 100 and 200:

[Queryable (Maxtop = +)] public IQueryable Get (int projectid)

[Queryable (Maxskip = $)] public IQueryable Get (int projectid)

With Allowedorderbyproperties, you can sort the results by the id attribute, because sorting by other attributes can be slow:

[Queryable (allowedorderbyproperties = "Id")] public IQueryable Get (int projectid)

If the client is allowed to use an equality comparison within $filter, it should be validated with Allowedlogicaloperators:

[Queryable (allowedlogicaloperators = allowedlogicaloperators.equal)] public IQueryable Get (int projectid)

If you set Allowedarithmeticoperators to None, you can turn off arithmetic operations in $filter:

[Queryable (allowedarithmeticoperators = allowedarithmeticoperators.none)] public IQueryable Get (int projectid)

You can also use the Allowedfunctions property to restrict the use of functions in $filter:

[Queryable (allowedfunctions = allowedfunctions.startswith)] public IQueryable Get (int projectid)

The above code means that the StartsWith function can only be used in $filter.

Hongmei also demonstrates query validation in high-level scenarios, such as customizing default validation logic for $skip, $top, $orderby, $filter, and using odataqueryoptions to validate queries.

Related articles:

OData Developers reference:http://www.odata.org/developers/

OData in Asp.net:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api

limiting OData Query options:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/ Supporting-odata-query-options

OData security:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-security-guidance

Add an OData Feed to Your App Using Web api:http://marknic.net/2013/03/02/add-an-odata-feed-to-your-app-using-web-api/

Working with OData Queries in ASP. NET Web api:http://www.codeguru.com/csharp/.net/ Working-with-odata-queries-in-asp.net-web-api.htm

Validate with the Queryable API in the ASP. NET Web API OData: HTTP://WWW.INFOQ.COM/CN/NEWS/2013/02/QUERYABLE-API

A new option to create OData: Web api:http://msdn.microsoft.com/zh-cn/magazine/dn201742.aspx

Building OData Service Using ASP. NET Web API Tutorial–part 1

Sample code Download: Http://files.cnblogs.com/shanyou/WebApiOData.zip

Go ASP. NET Web API support for OData

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.