Thursday 16 July 2020

How to Improve Web API Performance

Web Api: This is a framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
It is light weight architecture and good for devices which have limited bandwidth like smart phones.

In this page, we will discuss about the techniques to improve the Web API performance.

1: JSON serializer over XML:
JSON serializer use JSON Formatter and by default Web API provides media-type formatters for both JSON and XML.A media type formatter is used to read CLR objects from an HTTP message and write the CLR object in HTTP message body.
JSON serializer is highly recommend and it very faster compare to other Serlializer like XML.

2: Asynchronous Task Based WebAPI :
     Async Web API action help to increase the number of concurrent HTTP requests Web API can handle. We can implement asynchronous programming for web api controller by using keywords async, Task, await

public class UserController : ApiController
{       
  public async Task<IHttpActionResultRead()
  {
   var data = await _db.UserMaster.ToListAsync();
   return Ok(data);
  }
 }

3: Cache Data:
Web API  does not provide the output Caching attribute to cache web api response but you can Cache data in memory to process same future request without hitting database and it improve the performance of ASP.NET Web API and Microsoft provides the System.Runtime.Caching library for memory caching. 

4: Multi Result sets or combined results
Web API should return as many objects as you can in one Web API request and combining objects into one aggregate object and It reduce the number of HTTP request to web API

Example : Aggregate Object ‘UserScreenData’

class UserScreenData
{
public List<StateStates { getset; }
public List<CountryCountries { getset; }
}

 Web API Method to return Aggregate object

public async Task<IHttpActionResultGetScreenData()
{
 UserScreenData screen = new Controllers.UserScreenData();
 screen.State = await _db.State.ToListAsync();
 screen.Countries = await _db.Country.ToListAsync();
 return Ok(data);
}

5: Implement compression
You should use compression techniques to compress the data that is transmitted over the wire. You can use GZip or Deflate compression on your Web API to compress data transferred between the server and the client. You can do the compression at the IIS level or by using a custom delegating handler or even using a custom action filter. You can learn more on how you can achieve this from  Click here

Below example you can use in Dotnet Core WebAPI.
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression();
    services.Configure<GzipCompressionProviderOptions>(options => {
        options.Level = CompressionLevel.Fastest;
    });
}

6: Use classic ADO.NET if possible
Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

The Dapper and the  hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

But if you write your data access logic in optimize ways in EF Core, then definitely it improves the performance of the application. Here, we have some of the techniques which will increase the performance.
  1. Use No Tracking while getting the data which is the only read-only purpose. It improves performance.
  2. Try to filter the data on the database side, don’t fetch the whole data using query and then filter at your end. You can use some function available in EF Core like Where, Select which help you to filter the data on the database side.
  3. Retrieve only the required number of records which is necessary using the help of Take and Skip. You can take one example of paging where you can implement Take and Skip while clicking on the page number.
Let's take one example and try to understand how we can optimize the EF Core query using Select and AsNoTracking.

public async Task < PaginatedList < Post >> GetPagedPendingPosts
     (int pageIndex, int pageSize, List<Category> allowedCategories)
{
  var allowedCatIds = allowedCategories.Select(x => x.Id);
  var query = _context.Post
    .Include(x => x.Topic.Category)
    .Include(x => x.User)
    .Where(x => x.Pending == true && allowedCatIds.Contains(x.Topic.Category.Id))
    .OrderBy(x => x.DateCreated);

  return await PaginatedList<Post>.CreateAsync(query.AsNoTracking(), pageIndex,                                                                 pageSize);
}



0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives