NET Reference Sheet4
NET Reference Sheet4
NET Core
In ASP.NET Core, a Web API controller is a class that handles HTTP requests from clients (like
browsers, mobile apps, or other services). It is designed to return data (usually in JSON or XML
format) rather than rendering a view, which is typical in MVC applications.
A Web API controller typically handles CRUD (Create, Read, Update, Delete) operations on a
resource. This makes it an ideal choice for building RESTful APIs.
A RESTful API (Representational State Transfer) follows a set of constraints to ensure consistency,
scalability, and easy-to-understand resource management over HTTP. The key principles of REST
include:
• Stateless Communication: Each request from the client to the server must contain all the
necessary information for the server to understand and ful ll the request.
• Client-Server Architecture: The client and server operate independently of each other.
• Uniform Interface: The interactions with resources are consistent, typically using HTTP
methods like GET, POST, PUT, DELETE.
Before creating the controller, let’s de ne a model that will represent the data. This model will be
used to retrieve and manipulate data.
csharp
CopyEdit
// Book.cs
namespace OnlineBookStoreAPI.Models
{
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public double Price { get; set; }
fi
fi
fi
}
}
2. Set Up the Database Context
For data retrieval, we need to set up a DbContext to interact with the database. The DbContext
provides methods like FindAsync(), ToListAsync(), etc., that allow us to interact with
the database in a strongly-typed manner.
csharp
CopyEdit
// AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using OnlineBookStoreAPI.Models;
namespace OnlineBookStoreAPI.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext>
options) : base(options) { }
Now, let’s create the BookController that will manage the HTTP requests and interact with the
database to retrieve book data. We’ll inject the AppDbContext into the controller and de ne
actions for retrieving data.
csharp
CopyEdit
// BookController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OnlineBookStoreAPI.Data;
using OnlineBookStoreAPI.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OnlineBookStoreAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BookController : ControllerBase
fi
{
private readonly AppDbContext _context;
// GET: api/Book
[HttpGet]
public async Task<ActionResult<IEnumerable<Book>>>
GetBooks()
{
return await _context.Books.ToListAsync();
}
// GET: api/Book/5
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBook(int id)
{
var book = await _context.Books.FindAsync(id);
if (book == null)
{
return NotFound();
}
return book;
}
}
}
Explanation:
• Route Attribute: The [Route("api/[controller]")] sets the base route for the
controller. [controller] automatically maps to the controller's name (e.g.,
"BookController").
• GET /api/Book: This action returns a list of all books. The ToListAsync() method
retrieves all books from the database asynchronously.
• GET /api/Book/{id}: This action returns a speci c book by its ID. If the book is not found,
it returns a 404 Not Found status.
csharp
CopyEdit
using Microsoft.EntityFrameworkCore;
using OnlineBookStoreAPI.Data;
options.UseSqlServer(builder.Configuration.GetConnectionStrin
g("DefaultConnection")));
builder.Services.AddControllers();
app.UseAuthorization();
app.MapControllers();
app.Run();
• The AddDbContext method registers AppDbContext and con gures it to use a SQL
Server database. You can replace UseSqlServer() with another provider like
UseMySql() depending on the database you're using.
bash
CopyEdit
dotnet run
Once the application starts, you can access the API endpoints:
You can use Postman or a browser to make GET requests to these endpoints and see the returned
data.
When building APIs, handling edge cases like 404 Not Found, 400 Bad Request, and 500 Internal
Server Error is important.
fi
fi
fi
You can use try-catch blocks to handle errors in your controller:
csharp
CopyEdit
[HttpGet("{id}")]
public async Task<ActionResult<Book>> GetBook(int id)
{
try
{
var book = await _context.Books.FindAsync(id);
if (book == null)
{
return NotFound();
}
return book;
}
catch (Exception)
{
return StatusCode(500, "Internal server error");
}
}
This ensures that if an error occurs during the data retrieval process, a 500 Internal Server Error is
returned.
A RESTful API is based on REST (Representational State Transfer) principles, which are a set
of constraints that allow you to build scalable and maintainable web services. RESTful APIs
typically use HTTP methods to interact with resources (data objects).
• GET: Retrieves data from the server (e.g., get all books or get a book by ID).
• POST: Creates new data on the server (e.g., add a new book).
3. Status Codes
• 200 OK: Request was successful.
By default, ASP.NET Core uses JSON as the data format for RESTful APIs. You can also con gure
it to return XML or other formats based on client requests.
◦ Ensure you use the correct HTTP status codes in responses (e.g., 200 for successful
requests, 404 for not found, etc.).
◦ Resources in your API should be named using plural nouns (e.g., /api/books
instead of /api/book).
3. Idempotent Operations:
◦ Ensure that GET and PUT operations are idempotent, meaning multiple calls should
have the same result.
◦ Use versioning in your API paths to ensure backward compatibility (e.g., /api/
v1/books, /api/v2/books).
Conclusion
Creating a Web API controller in ASP.NET Core allows you to build a robust and scalable system
for handling CRUD operations over HTTP. By following the principles of REST, you can create
clean, maintainable APIs that are easy to integrate with various client applications.
This guide should help you get started with building your own RESTful APIs in ASP.NET Core,
retrieving data, and implementing basic error handling. If you want to extend this API, consider
adding more advanced features such as authentication, pagination, ltering, and sorting.
fi
fi
Model Validation in ASP.NET Web API - ASP.NET 4.x
What is Model Validation?
In ASP.NET Web API, Model Validation refers to the process of verifying that the data provided
in HTTP requests is valid before performing any operations on it, such as saving it to a database.
This validation is essential to ensure the integrity of the application and protect it from invalid,
malicious, or incomplete data.
In ASP.NET Web API 4.x, model validation is done using data annotations and validation
attributes. These annotations are applied to model properties to enforce constraints like required
elds, length limits, or value ranges. When a request is received, the Web API checks whether the
model data is valid by running these validation rules.
1. Data Annotations
Data annotations are attributes that you can apply to properties in your model class to enforce
validation rules. Common annotations include:
• [Range]: Ensures that the value of a numeric property is within a speci ed range.
csharp
CopyEdit
// BookModel.cs
using System.ComponentModel.DataAnnotations;
namespace WebAPI.Models
{
public class Book
{
[Required]
public string Title { get; set; }
[Required]
[StringLength(100, MinimumLength = 5)]
public string Author { get; set; }
[Range(1, 1000)]
fi
fi
fi
public decimal Price { get; set; }
}
}
In the above example:
• The Title and Author properties are required, meaning they cannot be null.
In ASP.NET Web API 4.x, model validation is automatically triggered when the controller method
receives a request. If the model is invalid, the action method does not execute, and a 400 Bad
Request response is returned.
csharp
CopyEdit
// BookController.cs
using System.Web.Http;
using WebAPI.Models;
namespace WebAPI.Controllers
{
public class BookController : ApiController
{
[HttpPost]
public IHttpActionResult AddBook(Book book)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns all
validation errors
}