Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Sunday, March 22, 2026

Web API | Http Status Codes

 HTTP Status Code Families

1xx – Informational
  • Request received, processing continues
  • Rarely used in practice
  • Example: 100 Continue

2xx – Success
  • Request was successfully processed
  • Most common success responses
  • Examples:
    • 200 OK → Standard success
    • 201 Created → Resource created
    • 204 No Content → Success, no response body

3xx – Redirection
  • Further action needed to complete request
  • Client must follow redirect
  • Examples:
    • 301 Moved Permanently
    • 302 Found (Temporary Redirect)
    • 304 Not Modified → Cache use

4xx – Client Errors
  • Problem with the request (client-side issue)
  • Examples:
    • 400 Bad Request → Invalid input
    • 401 Unauthorized → Authentication required
    • 403 Forbidden → Access denied
    • 404 Not Found → Resource doesn’t exist

5xx – Server Errors
  • Server failed to fulfill a valid request
  • Examples:
    • 500 Internal Server Error → Generic failure
    • 502 Bad Gateway → Invalid upstream response
    • 503 Service Unavailable → Server overloaded/down
    • 504 Gateway Timeout → Upstream timeout

Saturday, February 21, 2026

Web API - Caching

Note: Response/Output cache handled by their respective middlewares and do not hit controller in subsequent requests until cache invalidated.
Data Cache (IMemorycache, Memcache, Redis): Managed by code, you check in code if data available in cache then serve else reproduce and serve.

1. Output Caching (Recommended for .NET 7+)

Starting in ASP.NET Core 7+, Microsoft introduced built-in Output Caching Middleware, which is the best way to cache full API responses.

Step 1: Register Output Caching

In Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOutputCache();

var app = builder.Build();

app.UseOutputCache();

app.MapControllers();

app.Run();

Step 2: Apply Caching to an Endpoint
[HttpGet]
[OutputCache(Duration = 60)]
public IActionResult GetProducts()
{
return Ok(GetProductsFromDatabase());
}

🔹 This caches the response for 60 seconds.
🔹 Works great for GET endpoints.


Advanced Example (Custom Policy)
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("MyPolicy", policy =>
policy.Expire(TimeSpan.FromMinutes(5))
.SetVaryByQuery("category"));
});

Then:

[OutputCache(PolicyName = "MyPolicy")]

2. Response Caching (HTTP Cache Headers)

This uses HTTP headers like Cache-Control. It works with browser/proxy caching.

Enable Middleware
builder.Services.AddResponseCaching();
app.UseResponseCaching();
Use Attribute
[ResponseCache(Duration = 60)]
[HttpGet]
public IActionResult GetProducts()
{
return Ok(data);
}

🔹 This sets HTTP headers.
🔹 It does NOT cache on the server by default.
🔹 Good for public APIs.


3. Data Cache 
In-Memory Caching (IMemoryCache)

Best when you want to cache data, not full HTTP responses.

Register
builder.Services.AddMemoryCache();
Use in Controller
private readonly IMemoryCache _cache;

public ProductsController(IMemoryCache cache)
{
_cache = cache;
}

[HttpGet]
public IActionResult GetProducts()
{
if (!_cache.TryGetValue("products", out List<Product> products))
{
products = GetProductsFromDatabase();

var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5));

_cache.Set("products", products, cacheOptions);
}

return Ok(products);
}

4. Distributed Caching (Redis, SQL Server)

For multi-server environments, use distributed cache.

Common choice:

  • Redis: Redis can store complex data types like Lists, arrays, Hash tables etc.

  • Memcached: Simple text string store 

Example Setup with Redis
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});

Then inject IDistributedCache.


FeatureMemcachedRedis
DistributedYesYes
ReplicationNo (basic)Yes
PersistenceNoYes
Data loss riskHigherLower
ComplexitySimpleAdvanced



Which One Should You Use?

ScenarioRecommended
Cache full API response    OutputCache
Scale across multiple servers    Redis (Distributed Cache)
Cache DB results only    IMemoryCache
Browser/proxy caching    ResponseCache

Best Practice Tips
  • Cache only GET requests.
  • Avoid caching user-specific data unless using VaryBy.
  • Always define expiration.
  • Invalidate cache on data update.
  • Use distributed cache in production with multiple instances.

Output cache and Response Cache both stores whole response handled by middleware, only difference is storage location. 

Response Caching vs Output Caching
FeatureResponse CachingOutput Caching
Where caching happensClient / Proxy (browser, CDN)Server (inside ASP.NET Core)
MiddlewareUseResponseCaching()UseOutputCache()
Actually stores response on server?NoYes
Performance benefit for serverMinimalSignificant
Best forPublic APIsHigh-performance APIs
IntroducedEarly ASP.NET Core versions.NET 7

Saturday, April 5, 2025

Web API | Json Web Token - JWT

Creating JWT -

  1. Import “Microsoft.AspNetCore.Authentication.JwtBearer” package from Nuget. 
  2. Select the algorithm. like HMACSHA256. 
  3. Creating the claims collection. Remember there are standard claims and you can add your own. 
  4. Create credentials object using algo and secret key.
  5. Generate token using claims and credentials.
  6. Add [Authorize] attribute to controller, then action methods of this controller will be authorized. 
JWT token has this format: Header.payload.signature
Header: Contains algorithm used to create JWT like HSA256
Payload: Contains information related to user and authentication
Signature: Created using Header and payload

JWT is encoded not encrypted, so never put critical information in it.



Validating JWT at Application


Validating JWT token in middleware



Refresh Token: This is sent by server along with jwt, when jwt expired client sends this refresh token to server and server generate new JWT and refresh token and sends to client.
Benefit of refresh token is that again and again client no need to send user credentials.

Storing JWT at client end:
In-memory: Using the application variable we can store the token when the application is running. this is for application session only.
Cookie: If you want to store beyond application session(log time). cookie is a good place.
Indexed DB, Session storage and local storage are prone to XSS attacks.
Create cookie using HTTP only. By doing so this cookie can not be read using JavaScript “document.cookie”. In other words cookie is safe from XSS attacks.


Below could be third party Google, amazon, facebook or self owned services -

Open Id: Used for authentication, you want to just know if the user exists in the system in or not. Like shopping sites , mobile applications , single sign on etc. 
OAUTH: Used for authorization, when third party application tries to access resources. 
Open ID Connect: Used for authentication plus authorization both, when you want to authenticate and authorize as well like intranet websites.

Identity Server: This is a free open source server that you can use to implement Open Id Connect and Auth. It is certified by OpenId Foundation.
Single Sign on: Organizations those use single sign on, they redirects requests to their Identity server from each of their web portals, user get authenticated get token from Identity server (like Okta) and can access the web portals.
Identity server could a third party like Okta.


Web API | Roles Vs Claims

 



Web API Facts

Web Api is REST based service on web works on http or https.

REST - Representational State Transfer 

Facts 

Rest Facts

  1. Client-Server model: Its client server model but there is no coupling, completely decoupled model.
  2. Statelessness: Web API is rest based service, is request has complete information to serve, there is no state management.
  3. Catchability: Data can be cached for better performance.
  4. Layered system: There might be multiple layers at service end, client doesn't need to care about it. When client calling an endpoint, that might be an intermediate endpoint.
  5. Uniform Interface - 
    • Unique identification
    • Resource manipulation through representation
    • Self descriptive message


Facts About Web API

  1. Web API controller inherit ControllerBase class while MVC controller inherits Controller class.
  2. Web API returns only data while MVC controller can return view or partial view as well.
  3. What is content Negotiation?
    Web API can return data format based on "Accept" request header.
  4. Content Negotiation
    ASP.NET Core Web API uses the Accept header to decide response format:
    Example:
    • Accept: application/json → returns JSON
    • Accept: application/xml → returns XML (if enabled)


  5. Web API Vs WCF



WCF Rest Vs WA Rest: Web API built for Rest only from start, while Rest is added with WCF later.

.Net Core | Web API Basics

Web API is REST based web service.

Why Web API?
  1. Reuse logic for internal application
  2. Reuse logic for external application
  3. Separation of concerns
  4. Security 
  5. Environment of multiple teams 

*DI is not only limited to controllers, any class implements injected interface can use them.
*Web application and Web API both can use same classes in .Net Core.

Some Facts to be noted about ASP.Net Core Web API:
  1. Attribute Routing: Actions automatically called without mentioning action name as routes mentioned above actions.

    [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET api/values
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/values/5
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }

            // POST api/values
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }

            // PUT api/values/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }

            // DELETE api/values/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
     
  2. Automatic Model validation: Posted model validated automatically no need to write any code. In case of any issue in validation, it returns with 400.
  3. Binding Source Attributes: 
    1. [FromBody]
    2. [FromForm]
    3. [FromQuery]
    4. [FromHeader]
    5. [FromRoute]
    6. [FromServices]

      // POST api/values
      [HttpPost]
      public void Post([FromBody] string value)
      {
      }
  4. Core Web API supports only Json in response by default, even if you request some other format type in request header.

    If you want to use XML format in request and response than 
    • You need to install below package from nuget.
      Microsoft.ASPNetCore.Mvc.Formatters.xml
    • Add AddXmlSerializerFormatters() method with AddMvc()
      public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc()
                      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                      .AddXmlSerializerFormatters();
              } 
  5. HttpClient is the class to call and use WebAPI from .Net classes.
  6. Calling WebAPI using client side script

    Add a new item

    function addItem() {
      const item = {
        name: $("#add-name").val(),
        isComplete: false
      };

      $.ajax({
        type: "POST",
        accepts: "application/json",
        url: uri,
        contentType: "application/json",
        data: JSON.stringify(item),
        error: function(jqXHR, textStatus, errorThrown) {
          alert("Something went wrong!");
        },
        success: function(result) {
          getData();
          $("#add-name").val("");
        }
      });
    }

    Update an exiting item 
    $.ajax({
      url: uri + "/" + $("#edit-id").val(),
      type: "PUT",
      accepts: "application/json",
      contentType: "application/json",
      data: JSON.stringify(item),
      success: function(result) {
        getData();
      }
    });

    Delete an item
    $.ajax({
      url: uri + "/" + id,
      type: "DELETE",
      success: function(result) {
        getData();
      }
    });

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...