0% found this document useful (0 votes)
8 views27 pages

Webapi Full Notes

The document provides an overview of creating a RESTful Web API using ASP.NET Core, detailing key principles, project setup, routing, HTTP methods, model binding, and validation. It includes examples of CRUD operations, JWT authentication, and the repository pattern for data access. Additionally, it covers how to consume APIs with tools like Swagger and Postman, and outlines the structure of a typical ASP.NET Core Web API project.

Uploaded by

Niranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

Webapi Full Notes

The document provides an overview of creating a RESTful Web API using ASP.NET Core, detailing key principles, project setup, routing, HTTP methods, model binding, and validation. It includes examples of CRUD operations, JWT authentication, and the repository pattern for data access. Additionally, it covers how to consume APIs with tools like Swagger and Postman, and outlines the structure of a typical ASP.NET Core Web API project.

Uploaded by

Niranjan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Asp.

net Core Webapi

Introduction to RESTful Services


REST stands for Representational State Transfer. It is an architectural style
used to build web services that allow different applications to communicate
over HTTP.

Key Principles:
• Stateless – Each request contains all required information.
• Client-Server – Frontend and backend are separate.
• Resource Based – Everything is treated as a resource.
• Uses HTTP Methods – GET, POST, PUT, DELETE.

Example JSON Response:


{
"id": 1,
"name": "Laptop",
"price": 50000
}

2. Creating a Web API Project in [Link] Core


Steps in Visual Studio 2022:

1. File → New → Project


2. Select [Link] Core Web API
3. Choose .NET 8.0
4. Enable OpenAPI (Swagger)
5. Click Create

Project Structure:
Controllers
Models
[Link]
[Link]

3. Routing and HTTP Methods


Routing decides which controller handles the request.

Controller Example:

[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
}

HTTP Methods:

GET – Retrieve data


POST – Insert data
PUT – Update data
DELETE – Remove data

Example GET Method:

[HttpGet]
public IActionResult GetProducts()
{
return Ok("List of products");
}

4. Model Binding and Validation


Model binding automatically converts HTTP request data into C# objects.

Example Model:

public class Product


{
public int Id { get; set; }

[Required]
public string Name { get; set; }

[Range(1000,100000)]
public decimal Price { get; set; }
}

Validation Example:

if(![Link])
{
return BadRequest(ModelState);
}

5. Testing APIs using Swagger or Postman


Swagger provides a browser UI for testing APIs.

Run the application and open:


[Link]
Postman Steps:
1. Select HTTP method
2. Enter API URL
3. Choose Body → JSON
4. Click Send

6. Consuming Web API in Other Applications


APIs can be consumed by:
• Angular
• React
• Mobile apps
• Desktop applications

Example using HttpClient in C#:

HttpClient client = new HttpClient();


var response = await
[Link]("[Link]

CRUD Operations with [Link] Core Web API

Model:

public class Employee


{
public int Id { get; set; }
public string Name { get; set; }
public double Sal { get; set; }
}
using [Link];
using [Link];
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly AppDbContext _context;
public EmployeesController(AppDbContext context)
{
_context = context;
}
// GET: api/employees
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>>
GetEmployees()
{
return await _context.[Link]();
}

// GET: api/employees/5
[HttpGet("{id}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
var employee = await _context.[Link](id);
if (employee == null)
return NotFound();
return employee;
}

// POST: api/employees
[HttpPost]
public async Task<ActionResult<Employee>> CreateEmployee(Employee
employee)
{
_context.[Link](employee);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetEmployee), new { id =
[Link] }, employee);
}

// PUT: api/employees/5
[HttpPut("{id}")]
public async Task<IActionResult> UpdateEmployee(int id, Employee
employee)
{
if (id != [Link])
return BadRequest();
_context.Entry(employee).State = [Link];
await _context.SaveChangesAsync();
return NoContent();
}

// DELETE: api/employees/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteEmployee(int id)
{
var employee = await _context.[Link](id);
if (employee == null)
return NotFound();
_context.[Link](employee);
await _context.SaveChangesAsync();
return NoContent();
}
}

JWT

What does JWT mean?


JWT = JSON Web Token
 JSON → data format
 Web → used in web / APIs
 Token → a secure string that proves who you are
JWT is a self-contained authentication token used mainly in Web APIs.
Login in a Web API

1. User enters username + password


2. API verifies credentials
3. API creates a JWT token
4. Token is sent to client
5. Client stores token
6. Client sends token with every API request
7. API validates token
8. API allows or denies access

Structure of JWT (VERY IMPORTANT)


JWT has 3 parts, separated by dots (.)

[Link]

Header
Contains:
 Token type
 Algorithm used
Payload (Claims)
Contains user data
{
"username": "niranjan",
"role": "Admin",
"exp": 1710000000
}

Signature
Ensures token is not tampered

Signature = Header + Payload + Secret Key


Only server can generate
Hacker cannot modify payload

[Link]
[Link]
[Link]
[Link]

JWT SETTINGS ([Link])

"Jwt": {
"Key": "ThisIsMySuperSecretKey12345",
"Issuer": "MyApi",
"Audience": "MyApiUsers",
"DurationInMinutes": 60
}
[Link]

using [Link];
using [Link];
using [Link];

[Link]([Link]
me)
.AddJwtBearer(options =>
{
[Link] = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,

ValidIssuer = [Link]["Jwt:Issuer"],
ValidAudience = [Link]["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
[Link]([Link]["Jwt:Key"]))
};
});

[Link]();

[Link]();
[Link]();
[Link]

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly AppDbContext _context;
private readonly IConfiguration _config;

public AuthController(AppDbContext context, IConfiguration config)


{
_context = context;
_config = config;
}

[HttpPost("login")]
public IActionResult Login(LoginDTO dto)
{
var user = _context.Users
.FirstOrDefault(x => [Link] == [Link]
&& [Link] == [Link]);

if (user == null)
return Unauthorized("Invalid credentials");

var token = GenerateToken(user);


return Ok(new { token });
}

private string GenerateToken(User user)


{
var claims = new[]
{
new Claim([Link], [Link]),
new Claim([Link], [Link])
};

var key = new SymmetricSecurityKey(


[Link](_config["Jwt:Key"]));

var creds = new SigningCredentials(key,


SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(


issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: [Link](60),
signingCredentials: creds
);

return new JwtSecurityTokenHandler().WriteToken(token);


}
}
PRODUCT MODEL

public class Product


{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

AUTH CONTROLLER (LOGIN → TOKEN)

[ApiController]
[Route("api/auth")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _config;

public AuthController(IConfiguration config)


{
_config = config;
}

[HttpPost("login")]
public IActionResult Login(string username, string password)
{
if (username != "admin" || password != "123")
return Unauthorized();
var token = GenerateToken(username);
return Ok(new { token });
}

private string GenerateToken(string username)


{
var claims = new[]
{
new Claim([Link], username)
};

var key = new SymmetricSecurityKey(


[Link](_config["Jwt:Key"]));

var creds = new SigningCredentials(key,


SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(


issuer: _config["Jwt:Issuer"],
audience: _config["Jwt:Audience"],
claims: claims,
expires: [Link](30),
signingCredentials: creds
);

return new JwtSecurityTokenHandler().WriteToken(token);


}
}
CRUD CONTROLLER (JWT PROTECTED)

[ApiController]
[Route("api/products")]
[Authorize] // 🔐 JWT required
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;

public ProductsController(AppDbContext context)


{
_context = context;
}

// GET ALL
[HttpGet]
public async Task<IActionResult> GetAll()
{
return Ok(await _context.[Link]());
}

// GET BY ID
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var product = await _context.[Link](id);
if (product == null)
return NotFound();
return Ok(product);
}

// CREATE
[HttpPost]
public async Task<IActionResult> Create(Product product)
{
_context.[Link](product);
await _context.SaveChangesAsync();
return Ok(product);
}

// UPDATE
[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, Product product)
{
if (id != [Link])
return BadRequest();

_context.[Link](product);
await _context.SaveChangesAsync();
return Ok(product);
}

// DELETE
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var product = await _context.[Link](id);
if (product == null)
return NotFound();

_context.[Link](product);
await _context.SaveChangesAsync();
return Ok("Deleted");
}
}

Claims

In [Link] Core authentication works using:


 Claims
 Identity
 Principal

Concept Meaning
Claim Information about user
Identity Who the user is
Principal The logged-in user (with identity)
What is a Claim?
A claim is a piece of information about the user.
Example:
new Claim([Link], username)
new Claim([Link], "Admin")
Examples of claims:
 Username
 Email
 Role
 UserId
What is ClaimsIdentity?

var identity = new ClaimsIdentity(claims, "MyCookieAuth");


This means:
"Create an identity for this user using these claims and this
authentication scheme."
It contains:
 Claims (user data)
 Authentication type ("MyCookieAuth")
Think like:
🪪 Identity Card of user

"MyCookieAuth" means?
It matches this in [Link]:
[Link]("MyCookieAuth")
.AddCookie("MyCookieAuth", options =>
{
[Link] = "/Account/Login";
});

So [Link] knows:
👉 This identity uses cookie authentication.

What is ClaimsPrincipal?

var principal = new ClaimsPrincipal(identity);


This wraps the identity into a user object.
Think like:
👤 Principal = The logged-in user
It represents:
 Current logged-in user
 Stored in HttpContext
Real Flow After Login
When you call:
await [Link]("MyCookieAuth", principal);
[Link] Core:
1. Stores user info in a Cookie
2. On next request → Reads cookie
3. Sets:
[Link]
Now you can access:
[Link]
[Link]("Admin")

Example
If user logs in as:
Username = admin
Role = Admin
Then you can do:
<h2>Welcome @[Link]</h2>
Or:
@if ([Link]("Admin"))
{
<a href="/Admin">Admin Panel</a>
}

Simple Real-Life Example


 Claims → Name: Niranjan, Role: Admin
 Identity → ID card created
 Principal → The person holding that ID card
Repository Pattern

What is Repository Pattern?


Repository pattern separates data access logic from business logic.

Without Repository:
Controller → DbContext
With Repository:
Controller → Repository → DbContext
This improves
• Maintainability
• Testability
• Clean Architecture

Repository Pattern Architecture


Controller
|
Service Layer (optional)
|
Repository
|
Entity Framework Core
|
Database

Project Structure
JwtAuthProject

├── Controllers
│ [Link]
│ [Link]

├── Models
│ [Link]
│ [Link]
│ [Link]

├── Data
│ [Link]

├── Repository
│ [Link]
│ [Link]

├── Views
│ Auth
│ [Link]
│ Product
│ [Link]
│ [Link]

├── [Link]

Models
User Model
using [Link];
public class User
{
public int Id { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}

Product Model
using [Link];
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
}

Login ViewModel

public class LoginViewModel


{
public string Username { get; set; }
public string Password { get; set; }
}

DbContext
using [Link];
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
}

Repository Layer
Repository handles database operations.

Interface

public interface IProductRepository


{
Task<List<Product>> GetAll();
Task<Product> GetById(int id);
Task Add(Product product);
Task Update(Product product);
Task Delete(Product product
}
Implementation

using [Link];
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _context;
public ProductRepository(AppDbContext context)
{
_context = context;
}
public async Task<List<Product>> GetAll()
{
return await _context.[Link]();
}
public async Task<Product> GetById(int id)
{
return await _context.[Link](id);
}
public async Task Add(Product product)
{
_context.[Link](product);
await _context.SaveChangesAsync();
}
public async Task Update(Product product)
{
_context.[Link](product);
await _context.SaveChangesAsync();
}
public async Task Delete(Product product)
{
_context.[Link](product);
await _context.SaveChangesAsync();
}
}
Service Layer
Service layer contains business logic.

Product Service Interface


public interface IProductService
{
Task<List<Product>> GetProducts();
Task AddProduct(Product product);
}

Product Service
public class ProductService : IProductService
{
private readonly IProductRepository _repo;
public ProductService(IProductRepository repo)
{
_repo = repo;
}
public async Task<List<Product>> GetProducts()
{
return await _repo.GetAll();
}
public async Task AddProduct(Product product)
{
await _repo.Add(product);
}
}

JWT Helper
using [Link];
using [Link];
using [Link];
using [Link];
public class JwtHelper
{
public static string GenerateToken(User user)
{
var key = [Link]("SuperSecretKey123");
var claims = new[]
{
new Claim([Link], [Link]),
new Claim([Link], [Link])
};
var token = new JwtSecurityToken(
claims: claims,
expires: [Link](1),
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}

Auth Service
public interface IAuthService
{
Task<string> Login(LoginDTO dto);
Task Register(RegisterDTO dto);
}

AuthService Implementation
public class AuthService : IAuthService
{
private readonly AppDbContext _context;
public AuthService(AppDbContext context)
{
_context = context;
}
public async Task Register(RegisterDTO dto)
{
var user = new User
{
Username = [Link],
Password = [Link],
Role = [Link]
};
_context.[Link](user);
await _context.SaveChangesAsync();
}
public async Task<string> Login(LoginDTO dto)
{
var user = _context.Users
.FirstOrDefault(x => [Link] == [Link]
&& [Link] == [Link]);
if (user == null)
return null;
return [Link](user);
}
}

Auth Controller
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IAuthService _service;
public AuthController(IAuthService service)
{
_service = service;
}
[HttpPost("register")]
public async Task<IActionResult> Register(RegisterDTO dto)
{
await _service.Register(dto);
return Ok("User Registered");
}
[HttpPost("login")]
public async Task<IActionResult> Login(LoginDTO dto)
{
var token = await _service.Login(dto);
if (token == null)
return Unauthorized();
return Ok(token);
}
}

Product Controller
using [Link];
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
private readonly IProductService _service;
public ProductController(IProductService service)
{
_service = service;
}
[HttpGet]
public async Task<IActionResult> GetProducts()
{
return Ok(await _service.GetProducts());
}
[Authorize(Roles="Admin")]
[HttpPost]
public async Task<IActionResult> AddProduct(Product product)
{
await _service.AddProduct(product);
return Ok("Product Added");
}
}

[Link] (JWT Configuration)


[Link]([Link]
me)
.AddJwtBearer(options =>
{
[Link] = new TokenValidationParameters
{
ValidateIssuer=false,
ValidateAudience=false,
ValidateLifetime=true,
ValidateIssuerSigningKey=true,
IssuerSigningKey=new SymmetricSecurityKey(
[Link]("SuperSecretKey123"))
};
});

Database Tables
Users
create table Users
(
Id int identity primary key,
Username varchar(50),
Password varchar(50),
Role varchar(20)
)
Products
create table Products
(
Id int identity primary key,
Name varchar(100),
Price decimal(10,2)
)

API Endpoints
Method Endpoint Description
POST /api/auth/register Register user
POST /api/auth/login Login and get token
GET /api/product Get products
POST /api/product Add product

Swagger Test Flow


Register user
POST /api/auth/register
Login
POST /api/auth/login
Copy JWT Token
Click Authorize in Swagger
Bearer TOKEN
Call APIs

You might also like