Loading...
...
Posted by Firuza Polad on September 20, 2025

Web Services

are standart methods that allow different application or system to communicate and share data over internet or network. Are designed to be loosely coupled, meaning changes in 1 service don't impact others. They use standart protocols HTTP(S), SOAP and formats XML,JSON and architecture style REST to facilitate communication. There are 2 types of web services:

  • 1. SOAP based services: it is a traditional web service or ASMX, ties to SOAP, meaning both: server and client must communicate using SOAP based XML messages. Run over HTTP(S) protocol, but use SOAP format, what does it mean? HTTP is just used to carry SOAP message from client to server and back again, and SOAP protocol define SOAP message structure. The message itself is wrapped in xml. Example: client send request which contains SOAP message, the request header has Content-Type: text/xml and request body has actual message with XML structure, server process message and send back response in another HTTP response which is also XML.

    - SOAP: simple object access protocol, is a messaging protocol that defines how messages should be structured and exchanged between systems. It use XML format for request and response messages, is more rigid compared to REST and include additional features like WS-Security (secure communication). More complex and heavyweight. Mostly used in enterprise-level applications.

    - XML: eXtensible markup language, it's format message, define set of rules for encoding, documents which is readable by both humans and machine. Commonly used in SOAP based web service, configuration files, data storage, data exchange. SOAP messages are always encoded in XML, and includes Header,Body,Service for thing like security,routing,message,methods. SOAP messages are encoded in XML, but XML is only the format. The actual transport happens via protocols like HTTP, SMTP, or TCP. HTTP(S) is the most common.

    TCP Transmission control protocol connection is created between sender and receiver before any data sent, if an error occurs then TCP will retransmit it, provide robust error detection. Example: HTTP(S), SMTP, SSH we use when we need reliable and error checked communication
    UDP User datagram protocol is no formal connection, it is created between sender and receiver, data is sent as individual packets without ensuring that receiver is ready. Don't guarantee anything, provide basic error detection but faster than TCP as it does not involve overhead of connection setup

    ~ What is WSDL(Web Service Description Language) and how accessed in SOAP?: It is a XML file define how the service can be called, what parameters it except, and what data it returns. In SOAP web service, WSDL is an XML-based language, act as a format contract between a web service and the client to understand how to communicate, describe how SOAP service works, what client need to send and receive. How works?: When web service is deployed, it creates ?wsdl file ending (http://example.com/mywebservice?wsdl), client access this URL and understand service structure, methods and data types it has, then generate client-side code to interact with SOAP service. Use tool like wsdl.exe to generate proxy classes, ultimately make request to server using generated code, it send an XML message based on structure defined in file. SOAP service check request to ensure it conform the structure in .wsdl then process request and send back SOAP response.

    ~ WS*-Security: adds security mechanism to SOAP messages at the message level instead of relying on transport level security like HTTPS. Commonly use XML signature and ensure that message has not been tampered during transfer and stay confidential. Uses encryption to protect message, ensure that the message comes from a trusted sender. Provide a way to include credentials directly in the SOAP message, allowing for flexible authentication. How works?:

    HEADER The security information (digital signature, encrypted data, tokens) is placed SOAP header. This Header are processed by the web service
    SIGNATURE Ensure integrity and authenticity of message, the SOAP message are signed using sender's private key. The recipient verifies the signature using the sender's public key, ensuring that the message has not been altered and it comes from a trusted sender. Private key (of sender) is used for signing, Public key (of sender) is used for verifying. Example: Alice create SOAP message, sign the message with her private key, then who has a public key will know it have been signed by Alice and attach this sign to SOAP message in WS-Header. Bob verifies the signature using Alice's public key. Ensure that message is from Alice and has not been tampered. Signing = integrity + authenticity (private key sign, public key verify).
    ENCRYPTION Ensure confidentiality of message, the SOAP message is encrypted using the recipient's public key and only recipient can read message by decrypt their private key. Private key (of recipient) is used for decrypting, Public key (of recipient) is used for encrypting. Example: Alice take entire SOAP message (include signature), encrypts the message using Bob's public key, this ensure that only Bob who has private key can decrypt and read message. Encryption = confidentiality (public key encrypt, private key decrypt).

    HTTP: Hypertext transform protocol, is a transport protocol used to receive and send messages over the internet. RESTfull services are relies on HTTP. It has methods:

    GET

    Used to retrieve data from a web service (e.g., fetching a list of users)

    POST

    Sends data to the web service (e.g., creating a new user).

    PUT

    Updates existing data in the service (e.g., updating user details).

    DELETE

    Removes data (e.g., deleting a user)


    HTTPS: Hypertext transform protocol secure is a secure version of HTTP, it use SSL/TLS (secure socket layer/ transport layer security) encryption to protect sensitive data (like payment details) is sending between client and server.

    WS* vs HTTPS: While HTTPs only protect data in transit (between 2 points), if the message is routed through multiple system, it gets decrypted/encrypted at each intermediary point. On the other hand, WS* keep security inside the message itself, so it stays protected end-to-end, even intermediaries.

    Examples:
    //SOAP

    <soap:Envelope xmlns:soap=""> //begining and end of soap 
      <soap:Header>   //contain additional info like security, routing 
      </soap:Header>   
      <soap:Body> //actual data in here 
          <GetUserDetails> 
            <UserId>123</UserId> 
          </GetUserDetails> 
      </soap:Body> 
    </soap:Envelope>
    
    //XML FORMAT
    <person>   
      <name>Firuza Polad</name>  
      <age>28</age>  
      <isEmployed>true</isEmployed> 
    </person>
    
    //MESSAGE FORMAT = how requests/responses are structured inside SOAP
    <message name="GetWeatherRequest"> //Describes the messages used (input/output). 
        <part name="city" type="xsd:string" /> 
    </message> 
    
    <portType name="WeatherPortType">  // Defines the operations (methods) the service supports. 
        <operation name="<binding name="WeatherBinding" type="tns:WeatherPortType">"> 
          <input message="tns:GetWeatherRequest"/> 
          <output message="tns:GetWeatherResponse"/> 
        </operation> 
    </portType> 
    
    <binding name="WeatherBinding" type="tns:WeatherPortType">  //Specifies how the service is accessed (usually over HTTP). 
    .. 
    </binding> 
    
    <service name="WeatherService"> //Contains the service endpoint information. 
    .. 
    </service>
    


  • 2. RESTfull based services: over a time, web service also include RESTfull services, this service use standart HTTP methods and REST architecture style to perform operation and return json/xml as response. Restfull web service is considered an API.

    - REST: representational state transfer, is an architecture style that use standart HTTP methods to perform operation. It relies on HTTPS for security, stateless (each request from the client to the server must contain all information necessary to understand and process that request, the server does not store session information between different request), meaning each request from client must contain all necessary information to complete the request. Are lightweight, easy to implement, return data in format like JSON,XML,HTML etc. Usage in Web/Mobile applications due its simplicity.

    - JSON:JavaScript object notation, is a lightweight message format that is easy for human to read and write, for machine to parse and generate. Used for transfer data between server and web application. Commonly used in RestFull web services, AJAX, API, config file. JSON consist of key-value pairs enclosed in curly braces {}. Client application can easily parse the JSON response and display the data in the UI. And is language independent. Data can be organized as:

    Objects Also knows as dictionaries or maps and represented by key and value pair.
    Arrays List of values, typically enclosed with brackets [].

    Parsing JSON Converting a JSON string into a data structure(like object)
    Serializing JSON Converting a data structure into a JSON string for transmission or storage.
    {
        "name": "Firuza Polad",
        "age": 28,
        "isEmployed": true,
        "skills": ["JavaScript", "HTML", "CSS"], // ARRAY
        "address": {  // OBJECT
            "street": "123 Main St",
            "city": "BAKU",
            "zip": "10001"
        }
    }
    
    // Parsing JSON
    
    const jsonString = '{"name": "Firuza ", "age": 28}';
    const obj = JSON.parse(jsonString);
    
    console.log(obj.name); // Output: Firuza
    
    // Serializing JSON
    
    const obj = { name: "Firuza ", age: 28};
    const jsonString = JSON.stringify(obj);
    
    console.log(jsonString); // Output: '{"name":"Firuza","age":28}'
    

    - JSON vs XML: Both formats are used for data exchange, but JSON is more popular in nowadays as we use fewer characters, structure is simpler which enable it to read and write manually, faster than XML. Ideal for mobile and web applications.


WCF

Windows Communication Foundation is a framework used for building robust web services in .NETA framework. Allow us to send data asynchronously from one end point to another endpoint. In here endpoint can be part of continuously available service hosted by IIS or it can be a service hosted in an application. There are 3 parts of WCF applications:

  • - WCF Service: core part of application, define BS logic and could be anything like calculating data, retrieving information from DB, process order. It has: Service contract: Specifies what operation are provided to clients Data contract: Specifies data structure that are exchanged between the service and client.

  • - WCF Service Host: is responsible for hosting the WCF service, like listening for incoming request, managing lifetime, provide necessary binding. Withous a Host, the service can not be accessed, it can be hosted such as IIS (international information service) which means service runs inside IIS as As application; Self-Hosting which means we can host service inside console application etc.; WAS(windows activation service) which means more advanced version of IIS and enable non-HTTP protocol like TCP.

  • - Service Client: is the application or service that use the WCF service, it calls the methods from service and use them, the client can be any kind of application (web,desktop,mobile) that needs to communicate with the service. The client typically uses a proxy class generated by tools,VS which acts as an intermediary to call service methods. Example: Calling GetWeather() method from proxy class which is use WeatherService (see below)

~ Fundamentals of WCF:

Message EndPoint
Is a communication between client and service. WCF use SOAP message (XML based) for communication by default. Message contain Header (for authentication) and Body (for actual data). Is the access point where WCF provide its functionality to clients, like an address where client can send request to service. Each service has at least 1 endpoint but can have multiple for different protocols. It has 3 important parts:
Address

location where service is hosted, like URL (http://localhost:8080/WeatherService)

Binding

define how communication happens between client and service, like protocols (HTTP,TCP), endpoint(text,data)

Contract

define interface what operations are provided by service, like methods available to clients. There are 2 type of contract (service and data, read above).


~ When use: Suppose we have 2 clients: One of them wants to use WebService which sends data over the network by using HTTP protocol and want reply in XML formati (HTTP + XML e.g., SOAP/REST over HTTP), the other client wants to use WebService which sends data over the network by using TCP protocol and replying in binary format (TCP + Binary). The problem in here is, we need to create 2 different Services for 2 different clients. WCF is solving this problem writing one single service which can be used by 2 different clients-either they want same protocol or a different protocol ex: basicHttpBinding → for HTTP + XML or netTcpBinding → for TCP + Binary. We don’t define the protocol name inside the WebService class itself, instead we configure it in the WCF configuration (app.config/web.config) under the <endpoint> element.
Without WCF we can create simpler,lighweight approach SOAP based service which can use ASMX. In application we choose ASP.NET Web Application (ASMX) template. But WCF offering more features like WS-* standarts, reliable messaging and more, so if need full SOAP features we use WCF on .NET framework. It only runs on Windows as part of .NET framework. In application we choose WCF Service Application app from template. If we need SOAP on cross-platform (Windows,Linux, MacOS) but limited features we use SoapCore library as WCF not supported on .NET Core (now .NET5/6/7/8). SoapCore is not typically used for client-side, is mainly used for server-side. If we want to build a client-side service we use ServiceModel.Http library, it allow the client-side functionality of WCF in .Net Core but itself does not support server-side. Key terms:

  • ServiceContract: Interface define service's operation, using [ServiceContract] and [OperationContract] attributes

  • DataContract: Class define data structure used by service.[DataContract] and [DataMember]



WCF WebService
ServiceContract and OperationContract used for defining WCF service WebService and WebMethod used for defining web service
Support HTTP(S) , TCP protocol Support only HTTP(S)
Hosted on IIS , WAS or Self containing hosting Hosted only IIS
Use tool to generate proxy classes Use tool to generate proxy classes
Use System.Runtime.Serialization Use Sysyem.Xml.Serialization

API

application programming interface, is set of rules and protocols that define how different software app can interact with each other. It doesn’t have to involve the Web. It has 2 types, such as local APIs (e.g., a C# class library) or remote APIs (e.g., REST APIs or SOAP APIs). Local API (No Internet) means: we're writing a C# desktop app to manipulate files. We use the .NET File API provided by the framework to perform tasks ( using the File and Directory classes and streams FileStream, StreamReader, StreamWriter ) like reading, writing, or deleting files.

WEB API: is type of Remote API allow different applications communicate with each other over WEB, using HTTP(S) as protocol. Commonly used to enable web app, mobile app and other system to interact with external services and exchange data. RESTful APIs (which use JSON or XML over HTTP) and GraphQL APIs are types of Web APIs. ASP.NET Web API (or just Web API) Used to build RESTful services. NOTE: All Web APIs are APIs, but not all APIs are Web APIs.

Characteristics

  • Uses standard HTTP methods like GET, POST, PUT, DELETE.
  • Stateless: each request must contain all necessary information. The server does not store session information between requests.
  • Typically exchanges data in JSON or XML.
  • Enables communication between systems built on different technologies (e.g., one Web API built in JavaScript, another in .NET).
  • Reusable across multiple platforms (web, mobile, desktop).

Usage

  • Many services offer public APIs to allow developers to integrate (e.g., payment gateways, social media platforms).
  • Mobile apps commonly use Web APIs to communicate with backend servers for retrieving data and performing actions (e.g., user authentication).
  • In microservices architecture, Web APIs are used to allow different services to communicate with each other.
  • Cloud services expose functionality via Web APIs, enabling developers to access features like data storage.

How works: Client using application (web, mobile) to request to webAPI, this request typically follow a URL structure and include any necessary parameters (query string, request body). Server hosting API request, interact with , perform operation and return response back to client, usually in JSON/XML formats. And client process and display this format response.

...

GET, POST, PUT, and DELETE in RESTful API Design


API vs WebService: Both are designed for communication over web. All Web Services are Web APIs, but not all Web APIs are Web Services.

Web Service Web API
Is a specific type of webAPI, are older, traditionally using SOAP (XML) or sometimes REST. e.g: Bank A wants to send transaction to Bank B and they need strong security and guaranteed message delivery. They use SOAP where message sent as XML over HTTP. Structure of message is complex with header/body/token and ensure validated before transaction is completed. Web services are stateless so we can't maintain user sessions in web services Include all type , RestApi/ Soap Web Service/ GraphqlApi. Are modern. e.g: we are building a mobile app, we need to get weather , so application make HTTP GET request to Restfull WebAPI and receive data as JSON, response is simple and perfect for mobile application that need real-time weather update.

What is the use of Accept and Content-Type Headers in HTTP Request? : These are important headers in Restful web services, defining format and type of data which is sent between client and server.

  • Accept Header: tells the server the type of content the client expects in the response. If the server can send data in the requested format, it does; otherwise, it may return an error or a different format.
    • application/json → For JSON data.
    • application/xml → For XML data.
    • text/html → For HTML data.
    • text/plain → For plain text.
  • Content-Type: tells the server the format of the data being sent in the request body. When the client sends data (like in a POST request), it must specify the format using this header.
    
                                    POST /api/users HTTP/1.1
                                    Content-Type: application/json
    
                                    {
                                    "name": "FS",
                                    "email": "firuza@example.com"
                                    }
                                  

What are the main return types supported in Web API? :different return types are supported based on the kind of response you want to send to the client.

  • void: indicate that API return nothing, used when we don't need to send any content back to client (delete operation)
  • HttpResponseMessage: represent return type for response message, which is sent from server to client after http request has made, useful when working with HttpClient class. Key properties:
    • StatusCode: type of HttpStatusCode, the status code returned by server such as 200 OK, 400 Not Found.
      using HttpClient client = new HttpClient();
      var response = await client.GetAsync("https://url");  //or HttpResponseMessage response = ...
                
    • Informational responses (100 – 199)
      • 100-client send header 1st, and waits for confirmation from server before sending body.
      • 102-server has received and is processing the request but no response is available.
    • Successful responses (200 – 299)
      • 200-server returning the requested data, used in GET,POST,PUT,DELTE
      • 201-server returning information, details: url,data,etc. used in POST
      • 204-there is no content in response. can be used in DELETE,PUT,POST.
    • Redirection messages (300 – 399)
      • 300-there are multiple possible options, server excepts the client choose one
      • 301-resource has been moved permanently to new URL.
    • Client error responses (400 – 499)
      • 400-bad request, could not understandable due to invalid syntax,missing prm etc
      • 401-requires authentication, either client didn't provide any credentials, or invalid credentials.
      • 403-when client is auth but doesn't have permission to access the resource.
      • 404-not found, server can not find the requested resource, doesn't exist or removed.
    • Server error responses (500 – 599)
      • 500-something went wrong on server side, but problem isn't showed. it is often logged by server.
    • Content: instance of HttpContent, provde method to read content asynchronously. it can be read as string/json/xml etc.
      string content = await response.Content.ReadAsStringAsync();
                
    • Header: collection of HTTP header received from server. include, content type, content length.
      HttpResponseHeaders headers = response.Headers;
                
    • IsSuccessStatusCode: Boolean property that checks if status code is in the range of successful. 2xx status code like 200 Ok, 201 Created etc.
      if (response.IsSuccessStatusCode){
          // Success logic
      }
                
    • EnsureSuccessStatusCode: throw an exception if response status code isn't successful.
      response.EnsureSuccessStatusCode();  // Throws an exception if status code is not 2xx
                

What is HttpClient? : is used to send HTTP request and receive HTTP response, we can use single HttpClient instance for mutliple requests. It is under System.Http.Net namespace. Use method of HTTP and works with HttpResponse. Support async programming, has methods:

  • GetAsync()- send Get Request to API. (post,put,delete also)
  • StringContent()- define request body, content type in Post request.
  • DefaultRequestHeader()- set header like Auth, Accept type.
  • it’s good practice to use IHttpClientFactory, it manage HttpClient instance and ensure reused properly.

Full example:

public class ApiService 
{ 
//private readonly HttpClient _httpClient; 
private readonly IHttpClientFactory _httpClientFactory; 

public ApiService(IHttpClientFactory httpClientFactory) 
{ 
//_httpClient=httpClientFactory.CreateClient(); 
_httpClientFactory = (IHttpClientFactory)httpClientFactory.CreateClient(); 
} 

public async Task<string> GetDataAsync() 
{ 
//var client = _httpClientFactory.CreateClient("FactoryClient"); IF WE HAVE SERVICE CONFIG 
//HttpResponseMessage responseMessage = await client.GetAsync("/repos/weather"); 

var client = _httpClientFactory.CreateClient(); 

HttpResponseMessage responseMessage = await client.GetAsync("https://api.example.com/"); 

if (!responseMessage.IsSuccessStatusCode) 
{ 
responseMessage.EnsureSuccessStatusCode(); 
} 

var content = await responseMessage.Content.ReadAsStringAsync(); 
return content; 
} 

public async Task<HttpResponseMessage> SendDataAsync(object data) 
{ 
var client = _httpClientFactory.CreateClient();  
data = "{\"name\":\"Firuza\"},{\"age\":\"27\"}";  

var content = new StringContent 
( 
JsonConvert.SerializeObject(data), 
Encoding.ASCII, 
"application/json" 
); 

HttpResponseMessage responseMessage = await client.PostAsync("https://api.example.com/", content); 

if (!responseMessage.IsSuccessStatusCode) 
{ 
responseMessage.EnsureSuccessStatusCode(); 
} 

return responseMessage; 
} 
}

IActionResult<T>: represent return type of action method in a class in ASP.NET Core. Part of MVC and used to response back to client. it is a base class, and derived type of ActionResult represent spesific type of HttpResponses. Common derived types:

  • OkResult: represent 200 OK (success with no content).
    public IActionResult MyAction() { return Ok(); }
  • OkObjectResult: represent 200 ok (success with content, like serialized object, such as JSON).
    public IActionResult MyAction() { 
    var data = new { Name = "Firuza", Age = 30 }; 
    return Ok(data); 
    }
  • JsonResult: represent 200 OK (success with json encoded content).
    public JsonResult MyAction() { 
    var data = new { Name = "Firuza", Age = 30 }; 
    return new JsonResult(data); 
    }
  • NotFoundResult: represent 404 (when specified method not found).
    public IActionResult GetUser(int id){ 
    var user=_service.getUserById(id); 
    if(user is null){ return NotFound(); //404 } 
    return Ok(user); 
    }
  • BadRequestResult: represent 400 (bad request).
    public IActionResult CreateUser(User userDTO){ 
    if(user is null || string.IsNullOrEmpty(userDTO.name)){return BadRequest(); //400} 
    _service.createUser(user); 
    return Ok();
    }
  • UnAuthorizedResult: represent 401 unauthorized response.
    public IActionResult Dashboard(){ 
    if(!User.IsInRole("Admin")){ return Forbid(); //401} 
    var data=_service.GetData(); 
    return Ok(data); 
    }
  • ContentResult: represent response with custom content.
    public IActionResult GetText(){ 
    var content="hello"; 
    return new ContentResult{ 
      Content=content; 
      ContentType=text/plain; 
      StatusCode=200; 
    } 
    }
  • StatusCode: represent custom status code from response.
    public IActionResult Custom(){ 
    return StatusCode(500,"internal server error"); 
    }
  • RedirectResult: represent response that redirect to another url.
    return Redirect("https://anotherURL.com");
  • RedirectToActionResult: represent response that redirect to another action in same/other controller.
    return RedirectToAction("Index");
  • IHttpActionResult: represent return type of action method is a class in ASP.NET WebAPI. Same ActionResult, but provide higher level abstraction, allow to return response like Ok(),BadRequest(), NotFound(). it is easier to use.
  • Task<IHttpActionResult>: async version of IHttpActionResult in WebAPI. Commonly used in async programming for non-blocking operations like DB calls.

What is HttpClient / IHttpClientFactory class?

Which of the following Open-source libraries is used by WEB API for JSON serialization? the primary one is Newtonsoft.JSON also known as Json.Net. it provide robust functionality for converting .NET object to JSON format. Ideal for complex scenarious.

class Person {   
string Name {get;set;} 
string Job {get;set;} 
} 

Person student=new Person {Name="F", Job="Dev"} 
string json=JsonConvert.SerializeObject(student); 
var obj=JsonConvert.DeseralizeObject<Person>(json); 

System.Text.Json is fast and doesn't use much computer memory, used for modern applications.

string json=JsonSerializer.Serialize(student); 
var obj=JsonSerializer.DeSerialize(string); 

NetJSON is lightweight, faster than both Newtonsoft and Text.Json. But not widely known as other.

string json=NetJSON.Serialize(student); 
var obj=NetJSON.Desiralize<Person>(json); 

Conclusion:

  • For ASP.NET Web API: The primary library is Newtonsoft.Json.
  • For ASP.NET Core App: The default is System.Text.Json, but Newtonsoft.Json can be added if desired.

JSON.stringfy() is js method used in client-side. Above methods used for servvice-side. It converts object into JSON string. used to comm with server.

const obj = { name: "Firuza", age: 28 }; 
const jsonString = JSON.stringify(obj); 
console.log(jsonString); // Output: {"name":"Firuza","age":28}

What is ASP.NET Web API routing? : is the process of directing incoming HTTP request to appropriate controller action based on request's URL and HTTP method.

  • Support attribute routing, which allows us to specify routes directly on controller action.
  • [Route] - define base root for API. we can also add constraint to Route to limit type of values, e.g: only int prm is accepted like:
    [Route("{id:int}")]
  • [ApiController] - enable modern routing, mark controller as API controller, enable automatic validation, return data as json format.
  • [HttpGet] - getting value from source, has Name properly to differentiate multiple GetRequests.

Example:

[ApiController]
[Route("api/controller")]
public class ProductsController : ApiController
{
    [HttpGet("{id}")]
    public IHttpActionResult GetById()  { // }

    [HttpGet(Name="GetAll")]
    public IHttpActionResult GetAllProducts()  { // }

    [HttpGet("name={name}", Name="GetName")]
    public IHttpActionResult GetName(string name)  { // }
}
  • Support convention routing, where we specify controller and action name.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
  • Support route template, where we define parameters which can be optional or required and can be any type (string, int)

Examples:

  • api/products - get all products
  • api/products/5 - product with ID=5

How to secure ASP.NET Web API?

  • Authentication
  • Authorization
  • HTTPS
  • Validation
  • CORS

OpenAPI

Also known as Swagger, standard form of defining RestfulAPI, describe structure of API, including endpoints, request/response formats, AUTH methods and other metadata. It helps to interact with API without reading large documentation. It uses JSON format. There are various tools working with OpenAPI like Postman.

After Install-Package Swashbuckle.AspNetCore we add services.AddSwaggerGen(); to register swagger configuration. Then use below code to enable Swagger middleware JSON doc, and UI:

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test1 Api v1");
});

AJAX

Asynchronous JavaScript and Xml, is a technique used to create more dynamic and interactive web app. It allows web page to request data from a server and update part of web page without reloading entire page.

  • ASYNC: meaning that the web page can send a request to the server and continue to function without waiting for a response. When the response arrives, the page is updated without needing to refresh or reload.
  • JS: handles the communication and processing of the server's response.
  • XML: modern AJAX commonly uses JSON to transfer data, but XML is still supported but less common.

Commonly used:

  • Form Submissions: Submitting form data to the server without refreshing the page.
  • Loading Data: Loading additional content (e.g., posts, comments) without refreshing the page.
  • Live Search: Providing search results as the user types (e.g., Google’s instant search).

How it works:

  1. User interacts with web page (clicking a button).
  2. JS makes async HTTP request to server using XMLHttpRequest (XHR) or new fetch() API.
  3. Server processes request (accessing DB) and sends response back in JSON format.
  4. JS receives server's response and processes data.
  5. Without refreshing entire page, it updates relevant part of page dynamically (display new data).
// OLDER approach using XMLHttpRequest


<button type="button" onclick="loadData()"> Load Data</button>
<div id="content"></div>

function loadData() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            document.getElementById("content").innerHTML = xhr.responseText;
        }
    };
    xhr.send();
}
// MODERN approach using fetch()

function loadData() {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(data => {
            document.getElementById('content').innerHTML = JSON.stringify(data);
        })
        .catch(error => console.error('Error:', error));
}

Mention what is the difference between AJAX and REST?

AJAX Is a client-side technique, allows a web page to send and receive data async from a server without refreshing an entire page; it updates part of web page. Use JS to make async request to server by using XMLHttpRequest() or fetch() methods. Can be either stateful or stateless. Ex: when we search for something in Google, AJAX is used to fetch search results.
REST Is an architectural style for web services and APIs. Uses HTTP methods to interact with resources on server in a stateless manner. Perform CRUD operations. 3rd party API used by developers to access tweets, weather, etc.

JWT

JSON web token, is an open standard used for securely transfer information between parties as a JSON obj, it is widely used for authorization and authentication, where server return token after successful user login, and use this token for subsequent request to access protected resource. Jwt is not encrypted by default, meaning data in Payload can be visible to anyone who has token. If sensitive data needs to transfer, encryption should be used in addition to signing. Has 3 concept:

Header has 2 part: The type of the token (which is "JWT" in this case). The signing algorithm used (e.g., HMAC SHA256 or RSA).

{
  "alg": "HS256",  // HMAC-SHA256
  "typ": "JWT"     // Token type is JWT
}

Payload: contains claims, typically user. It can be :

  • Regtistered: like sub (subject), iat (issued at), exp (expiration time), etc
  • Public: such as user details (name, email).
  • Private: defined by users to share information between parties that agree on 

{
  "sub": "2354",       // User ID
  "name": "Firuza",    // Name of the user
  "admin": true,       // Admin flag
  "iat": 1516239022    // Time when the JWT was issued
}

Signature: ensure token is not tampered, To create the signature, we combine the encoded header, encoded payload, and a secret key, using the algorithm specified in the header (e.g., HMACSHA256).

  • HS256 (HMAC + SHA-256) is a symmetric algorithm where the same key is used for both creating and verifying the signature.
  • RSA (RS256) is an asymmetric algorithm where a private key is used to sign the token, and a public key is used to verify it.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload), secretKey
)

The Header and Payload automatically created and encoded in JwtSecurityTokenHandler library(which provides methods to read, validate, and write JWTs) based on based on the SecurityTokenDescriptor informations. Inside SecurityTokenDescriptor we define header and payload. The header is generated automatically based on the signing credentials (SigningCredentials) and the type of algorithm you choose (in this case, HmacSha256Signature). The payload is generated based on Subject(claims) credentials and expires. Ex;

var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.Name, "John Doe"),
        new Claim(ClaimTypes.Role, "Admin")
    }),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(
        new SymmetricSecurityKey(key),
        SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);

Access Token: is a short lived token that allow the client to access specific resource, typically contains user information (claims) and permission (role). passed along with API request within Authorization header ; Authorization: Bearer <access_token> , ensure that user is authenticated and authorized to perform action. when login, then token is generated, then sends to client. client include this token for subsequent request. it has short life time like 15min/few hours for security. are not stored on the server or database, as they are stateles, usually stored on client side:

  • Local storage (common in single-page applications like React or Angular).
  • Session storage (if the session should expire when the browser is closed).
  • Memory (for short-lived storage, like in-memory storage which is cleared when the page is refreshed).

 // Store JWT in local storage 

localStorage.setItem("token", "your-jwt-token"); 

  

// Retrieve JWT from local storage 

fetch('/api/protected-resource', { 

  headers: { 

    'Authorization': 'Bearer ' + localStorage.getItem('accessToken') 

  } });  

Refresh Token

is a long lived token that allow the client to obtain a new access token without re-authenticating the user(without login again). When user login the server respond with 2 token: Access and Refresh tokens. But after access token expires , normally we would not be able to make any request, then client application automatically send the refresh token to the server to get a new Access Token. Keep user as logged in and have no longer expiration time. Are stored on the server or database, because they need to be validated and managed securely. Is also stored on client side (secure cookies). Are more sensitive as they have longer lifespan (weeks, months).

ValidateToken

is the process of checking if a given token (like AC) is valid. Include verifying its signature , checking if it has expired, and ensure the claims are legal. if token isn't valid the request rejected. When validating token, we use ClaimsPrincipal, It extract claims from token like ID, Role and server now can use these claims to authorize access to different resources. For validation we use TokenValidationParameters which specifes rules to validate token. It has:

  • ValidIssuer- check the issuer, ensure token was created by trusted authority
  • ValidAudence-check the audience, specifies who the token is intended for. if your API is expect token from example.com:
  • IssuerSigningKey- specifies the security key that was used for signIn. TokenValidator use this key to verify token's signature
  • ValidateIssuerSigningKey-verify signing key, that ensure signature is valid and hasn't been tampered.
  • ClockSkew- allow grace period for token expiration than its actual expiration
  • RequireExpirationTime-ensure that token not used indefinitely.

   
ValidateIssuer = true; 
ValidIssuer = "https://auth.yourapp.com"; 

ValidateAudience = true; 
ValidAudience = "https://api.example.com"; 

IssuerSigningKey = new SymmetricSecurityKey(key); // Your secret key 
ValidateIssuerSigningKey = true; 

ClockSkew = TimeSpan.FromMinutes(5); 
RequireExpirationTime = true; 

‘Encoding : rocess of converting data from one type to another. Allow data to be represented in safe format, then decoded back later.

  • Text Encoding: like UTF8, ASCII. Converting characters to binary so computer can store and process.
  • Data Encoding: like Base64. Converting data into to format, so can be transferred over HTTP

Decoding : convert encoded string back to its original form, like convert base64 to binary.

Base64 : is encoding scheme used to convert binary data into text format, so this encode data which can be transferred over HTTP, EMAIL, HTML. How works: Computer process and store data in binary (1,0) , but some protocols expect data as text. son base64 convert this binary data into string of characters. this characters can be A-Z, a-z, 0-1, + and / in JWT concept, we use Base64 to encode Header and Payload. In Email concept, we use to encode attachments. In HTML concept, we use to embed image or other files in HTML/CSS.

Base64URL : is used for encoding, which is similar to Base64 but with URL-safe characters.

How works :

  • - user send their credentials (name,pass) to server,
  • - server verifies the credentials and if valid then generate JWT token that include claims such as user's ID/role/expiration time.
  • - JWT is sent back to client at the end. And client needs to store data in local storage or cookie for e.g: user stays logged in
  • - for each subsequent request to access resource, server require authentication and client send jwt in the HTTP header (Authorization header with Bearer schema).
  • - then server receive JWT and validate it using signature. If token is valid and not expired, the server process request.
  • - since, JWT is stateless, server doesn’t store session information about users in DB, because all data included in token.

Advantages :

  • - JWT stores all information needed for authentication in token itself, allow server to remain stateless. And server doesn't need to manage session for each user.
  • - can be easily used across different domain/application, making them ideal for microservices architecture.
  • - because JWT are base64 encoded, they can be transferred efficiently via URL parameters or HTTP Header or inside cookie.

Disadvantages :

  • - not encrypted, if contain sensitive information it must encrypted. Because, anyone who has token can decode the payload (header and claims) and read its contents. Signature only ensure the integrity of token, doesn't hide information in token.

JWT encryption : can be done using JWE (json web encryption) standard. Ensure that content of token is unreadable by both side. We install library called System. IdentityModel.Tokens.Jwt and generate RSA:

  // Generate RSA keys 

RSA rsa = RSA.Create(); 

var rsaPublicKey = rsa.ExportParameters(false); 

var rsaPrivateKey = rsa.ExportParameters(true);  
Session Based JWT
The server stores user session data . e.g: user send credentials to server, if credentials are correct the server create session for user and store information in DB. Server has full control over session. The session identified by its unique SessionID. Then sever send this sessionID to client and store in cookie. For each subsequest request, client send this ID to back server using cookie and allow server to verify user's identity. It has expiration time (after30min logs out). better for traditional server-rendered applications. The server does not store any session data. The JWT containing all necessary information, and the client stores the cookie. Ideal for modern application like microservice.

OAuth

is a protocol that allow one application to access resource or perform action on a user without getting their password. Instead, it uses tokens to give permission for limited duration. Flow: application request permission to access resources, we give permission and application use token to access only what we allow. e.g: we want to sign up for app (fitness tracker) and allow app to access our google calendar to track our workout.

  • - we click login in application and select 'login with google'
  • - application redirects us to google's login page. And only google ask our credentials(password)
  • - then google ask, 'do you allow this app to access calendar?'
  • - after we allow, google sends authorization code to fitness application
  • - and application only exchange code for access token
  • - then application use this access token and fetch data in google calendar. This token is limited scope, which only have access to calendar , and expire a certain time
  • - google send requested calendar data to fitness application

Information
All diagrams, Folder structure, Code example in this blog were created by me using Lucid , Canva and IDE If you'd like to contribute, request more diagrams or text, or suggest improvements, feel free to contact me
© 2025 Firuza Polad. All rights reserved.

Let’s Connect

I’m open to collaboration, remote and freelance work!