Saturday, May 6, 2023

Web API Versioning.

 Implement the new feature without impacting the existing consumers we can solve this problem by API versioning.
When the business has started to grow and expand, new requirements arise. Due to this, we may need to provide more functionality in the existing APIs. However, existing Web API can be consumed by many clients so how to implement the new feature without impacting the existing consumers? We can solve this problem by versioning our API.

Different ways of implementing Versioning in Web API.
1.Query String
2. URL.
3. HTTP Header
There are other ways as well, like accept-header and content type.

Wednesday, April 12, 2023

How to improve performance of the Web API

1. Use Parallel Programming in Web API 

2. Compress the Result of Web API

By compressing the API Response, we have the following two advantages.
  • Data size will be reduced
  • Response time will increase (increasing the speed of the communication between the Client and Server.)
Using DotNetZIP.

2. 

Using Caching to Improve Performance


Monday, April 10, 2023

Otput caching in MVC/API

 Caching is used to improve the performance in ASP.NET MVC. Caching is a technique which stores something in memory that is being used frequently to provide better performance. In ASP.NET MVC, OutputCache attribute is used for applying Caching. OutputCheching will store the output of a Controller in memory and if any other request comes for the same, it will return it from cache result.


OutputCache attribute can have a parameter.

  1. [OutputCache(Duration = 60)]  
  2. public ActionResult Index() {  
  3.     var emps = from e in db.Employees  
  4.     orderby e.ID  
  5.     select e;  
  6.     return View(emps);  
  7. } 

VaryByPara

It describes cache will be stored on the basis of a parameter. Cache will be stored on the basis of the list of semicolon separated by a string.

The example of VaryByParam is given below.

https://www.c-sharpcorner.com/article/how-to-implement-caching-in-the-net-core-web-api-application/
  1. [OutputCache(Duration = 60, VaryByParam = "Id")]  
  2. public ActionResult Index(int Id) {  
  3.     var emps = from e in db.Employees where e.DeptID = Id  
  4.     orderby e.ID  
  5.     select e;  
  6.     return View(emps); 

What is difference between Rest and Restful API

 The REST API follows all the rules of the REST Architecture. It has a client-server, stateless, cacheable, layer system with a uniform interface, whereas the RESTful web applications have all the features of the REST architecture with unique additional features. The REST API has a separate system to handle application information.




Sunday, April 9, 2023

What is the purpose of webHostBuilder()

 The webHostBuilder() as the name suggests is a factory used to create a web host for a web application. This function also configures the bits needed by the web host to run the application. It is a part of Microsoft.AspNet.Hosting namespace.

What is content negotiation in ASP.Net Web API?

 Content negotiation is basically a process of selecting the best representation from multiple representations that are available for a given response.

 It simply allows one to choose rather than negotiate content that one wants to get in response. It is performed at the server-side. In simple words, 

it chooses the best media type for matters to return a response to an incoming request.


There are two types of headers available for content negotiation:

  • Content-Type: This header tells the server about the information that it will receive from the client.
  • Accept: This header shows the data format requested by the client from the server.
We know that there are three pillars of the internet, they are:
  • The resource
  • The URL
  • The representation

The formal definition of Content Negotiation is “the process of selecting the best representation for a given response when there are multiple representations available”.

By checking the “Accept” header, the Web API understands which representation the client is able to accept. For example, if we specify that the client can understand the following representation:
 
application/xml , application/json, text/javascript



What are the main return types supported in ASP. Net Web API?

 It supports the following return types:

HttpResponseMessage

IHttpActionResult

Void

Other types such as string, int, etc

How to register an exception filter globally?

 One can register exception filter globally using following code:

Web API global filters are registered through the HttpConfiguration object available to you in the Register method WebApiConfig.cs if you're using a project template with WebActivator:

public static void Register(HttpConfiguration config)
{
    //stuff before
    config.Filters.Add(new MyWebApiFilter());
    //stuff after
}

or otherwise in the global.asax.cs:

GlobalConfiguration.Configuration.Filters.Add(new MyWebApiFilter());

How to handle errors in Web API?

 One can use HttpResponseException, HttpError, Exception filters, register exception filters, Exception handlers to handle errors. Exception filter can be used to identify unhandled exceptions on actions or controllers, exception handlers can be used to identify any type of unhandled exception application-wide, and HttpResponseException can be used when there is the possibility of an exception.

Explain media type formatters.

 In web API, media type formatters are classes that are responsible for serialization data.

Web API can understand request data format in a better way and send data in a format that the client expects. It simply specifies data that is being transferred among client and server in HTTP response or request. 


JsonMediaTypeFormatter ->application/json, text/json

XmlMediaTypeFormatter ->application/xml, text/json



 

Tuesday, August 16, 2022

Consuming ASP.NET Web API REST Service In ASP.NET MVC Using HttpClient

 Steps to Consume Web API in MVC.


Step1: Install HTTP Client library from NuGet.

What is HttpClient?

HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.

Step2:Install WebAPI.Client library from NuGet


Step3: Add Model and Controller class.

Step4: 

Our hosted Web API REST Service includes these two methods, as given below.


GetAllEmployees (GET )

GetEmployeeById (POST ) which takes id as input parameter

We are going to call GetAllEmployees method which returns the all employee details ,The hosted web api REST service base URL is http://192.168.95.1:5555/ and to call GetAllEmployees from hosted web API REST service, The URL should be Base url+api+apicontroller name +web api method name as following,


http://192.168.95.1:5555/api/Employee/GetAllEmployees

In the preceding url

http://localhost:56290 Is the base address of web API service, It can be different as per your server.

api It is the used to differentiate between Web API controller and MVC controller request .

Employee This is the Web API controller name.

GetAllEmployees This is the Web API method which returns the all employee list.


using ConsumingWebAapiRESTinMVC.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace ConsumingWebAapiRESTinMVC.Controllers
{
    public class HomeController : Controller
    {
        //Hosted web API REST Service base url
        string Baseurl = "http://192.168.95.1:5555/";
        public async Task<ActionResult> Index()
        {
            List<Employee> EmpInfo = new List<Employee>();
            using (var client = new HttpClient())
            {
                //Passing service base url
                client.BaseAddress = new Uri(Baseurl);
                client.DefaultRequestHeaders.Clear();
                //Define request data format
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //Sending request to find web api REST service resource GetAllEmployees using HttpClient
                HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");
                //Checking the response is successful or not which is sent using HttpClient
                if (Res.IsSuccessStatusCode)
                {
                    //Storing the response details recieved from web api
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;
                    //Deserializing the response recieved from web api and storing into the Employee list
                    EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);
                }
                //returning the employee list to view
                return View(EmpInfo);
            }
        }
    }
}
C#


Thursday, July 21, 2022

Web API Securities JWT Token.

 What is JWT Token?

JWT stands for Jason Web Token.

Token-based security is commonly used in today’s security architecture. There are several token-based security techniques. JWT is one of the more popular techniques. JWT token is used to identify authorized users.

What is the JWT WEB TOKEN?

Open Standard: Means anywhere, anytime, and anyone can use JWT.

Secure data transfer between any two bodies, any two users, any two servers.

It is digitally signed: Information is verified and trusted.

There is no alteration of data.

Compact: because JWT can be sent via URL, post request & HTTP header.

Fast transmission makes JWT more usable.

Self Contained: because JWT itself holds user information.

It avoids querying the database more than once after a user is logged in and has been verified.


JWT is useful for:

Authentication

Secure data transfer

JWT Token Structure 

A JWT token contains a Header, a Payload, and a Signature. 







Header

Header contains the algorithms like RSA or HMACSHA256 and the information of the type of Token.

  1. {  
  2.    “alg” : ”” Algorithm like RSA or HMACSHA256  
  3.    “Type” : ”” Type of JWT Token  
  4. }  

Payload

Payload contains the information of rows, i.e., user credentials.

  1. {  
  2.    “loginname” : ”Gajendra”  
  3.    “password”:”123#”  
  4. }  
  • It contains claims.
  • Claims are user details or additional information

Signature

{ base64urlencoded (header) +”.”+ base64urlencoded (payload) +”.”+ secret }

  • Combine base64 encoded Header , base64 encoded Payload with secret
  • These provide more security.

  • A combination of all headers, payload and signatures converts into JWT TOKEN.

How Does JWT Work?

Step 1 :
 
Client logs in with his/her credentials.


Step 2:

Server generates a Jwt token at server side. 




 
Step 3 :                                                                                                                                                 
After token generation, the server returns a token in response.                                                       





Step 4:                                                                                                                               
Now, the client sends a copy of the token to validate the token. 


Step 5                                                                                                   
 
The server checks JWT token to see if it's valid or not.


Step 6 :                                                                                                                         
 After the token is validated, the server sends a status message to the client.





The server can trust the client because the JWT is signed, and there is no need to call the database to retrieve the information you already stored in the JWT.

To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that’s only sent in HTTP requests to the server. It’s never accessible (both for reading or writing) from JavaScript running in the browser.

https://blog.logrocket.com/jwt-authentication-best-practices/





Steps to Implement JWT Authentication in Asp.net Core

  • Understanding JWT Authentication Workflow.
  • Create Asp.net Core Web API project
  • Install NuGet Package (JwtBearer)
  • Asp.net Core JWT appsetting.json configuration
  • Asp.net Core Startup.cs - configure services add JwtBearer
  • Create Models User, Tokens
  • Create JWTManagerRepository to Authenticate users and generate JSON Web Token.
  • Create UserController - Authenticate action method.

https://codepedia.info/jwt-authentication-in-aspnet-core-web-api-token




 


                                                 



















Thursday, August 26, 2021

Web API Filters

 Web API Filters=>


Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.


Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.



Filter TypeInterfaceClassDescription
Simple FilterIFilter-Defines the methods that are used in a filter
Action FilterIActionFilterActionFilterAttributeUsed to add extra logic before or after action methods execute.
Authentication FilterIAuthenticationFilter-Used to force users or clients to be authenticated before action methods execute.
Authorization FilterIAuthorizationFilterAuthorizationFilterAttributeUsed to restrict access to action methods to specific users or groups.
Exception FilterIExceptionFilterExceptionFilterAttributeUsed to handle all unhandled exception in Web API.
Override FilterIOverrideFilter-Used to customize the behaviour of other filter for individual action method.

Web API Versioning.

 Implement the new feature without impacting the existing consumers we can solve this problem by API versioning. When the business has start...