Scroll to top

OPTIMIZE ASP .NET CORE USING ODATA


DigitalOnUs - December 15, 2020 - 0 comments

Are you looking for a way to optimize and do more with less code? Then you have reached the right place. In this blog, I am going to talk about the main feature of OData with which you can create an IQueryable interface that provides you a cleaner way to consume your endpoints.

What is Odata?

OData (Open Data Protocol) is a protocol that defines some practices for the creation and consumption of queryable REST APIs in a standard way.

This protocol uses some technologies like HTTP, AtomPub or JSON, and lets any client get information using the following rules:

  • Using JSON as a Data structure.
  • Use URL conventions for some operations like filtering, pagination, navigation and order.
  • Create operation using HTTP (GET, POST, PUT, DELETE).

Some of the features that OData provides:

  • Create filters for getting data
  • Sort and paginate data
  • Use the same endpoint for multiple HTTP requests
  • Write less code – Instead of creating multiple methods for getting certain information, you can expose that data and consume it using a query in the URL request

How to configure OData in our project?

Create a new ASP. NET Core project.

You have to install the next package:

Package name: Microsoft.AspNetCore.OData

Example: Install-Package Microsoft.AspNetCore.OData

After this, you need to configure OData in the Startup.cs class:

app.UseMvc(routeBuilder =>;
   {
      routeBuilder.EnableDependencyInjection();
      routeBuilder.Select().Filter().OrderBy().Expand().Count().MaxTop(10);
 
      routeBuilder.MapODataServiceRoute("api", "api", GetEdmModel(app.ApplicationServices));
   });


private static IEdmModel GetEdmModel(IServiceProvider serviceProvider)
{
   ODataModelBuilder builder = new ODataConventionModelBuilder(serviceProvider);
 
// you have to add this code for every entity that you will use
   builder.EntitySet("Auth")
           .EntityType
           .Filter()
           .Count()
           .Expand()
           .OrderBy()
           .Page()
           .Select();
   .. .. ..
   return builder.GetEdmModel();
}

After this configuration, the first thing that you need to do is in your controller. Use

the [ODataRoutePrefix] and inherit from the OData controller.

Example:

[ODataRoutePrefix("Auth")]
public class AuthController : ODataController

The second step is to modify the current method inside the controller. For that, you need to add the next data attributes and return the result as an IQueryable object.

Example:

[ODataRoute]
      [EnableQuery(PageSize = 20, AllowedQueryOptions = AllowedQueryOptions.All)]
      [HttpGet]
      public IActionResult Get()
      {
         return Ok(db.Auth.AsQueryable());
      }
 

After you follow these steps, you’re ready to start consuming your API using the OData query structure. This protocol is very extensive and you can create more complex implementations. For more detailed information, take a look at this Microsoft documentation:

https://docs.microsoft.com/en-us/odata/

These are some examples of the queries you can use to consume any endpoint in your API:

Select all the auth objects

(http://localhost:5000/api/Auth)

Result:

{
  "authUsers": [
    {Username:'Miguel'},
    {Username:'Ricardo'},
    {Username:'Alejandro'}
  ]
}

Select all the user objects where the username is equal to ‘Miguel’

(http://localhost:5000/api/Auth?$filter=Username= eq Miguel’)

Result:

{
  "authUsers": [
    {Username:'Miguel'}
  ]
}

For ordering the results, you can use the command $orderby 

For selecting only certain properties, you can use the command $select 

Conclusion 

If you need to speed up your development time, the OData protocol is very useful and it does not take more than 10 minutes to implement this standard. Even though it is very useful, it won’t always be the best way to speed up your app as that would depend on your app requirements.

By – Miguel Rodríguez, Senior Full Stack Developer

Related posts