0% found this document useful (0 votes)
6 views8 pages

NET Reference Sheet4

This document provides a comprehensive guide on creating a Web API controller in ASP.NET Core, detailing the definition of Web API controllers, RESTful APIs, and the steps to create a controller for data retrieval. It includes code examples for setting up models, database contexts, and handling HTTP requests, as well as best practices for building RESTful APIs. Additionally, it covers error handling and model validation in ASP.NET Web API 4.x.

Uploaded by

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

NET Reference Sheet4

This document provides a comprehensive guide on creating a Web API controller in ASP.NET Core, detailing the definition of Web API controllers, RESTful APIs, and the steps to create a controller for data retrieval. It includes code examples for setting up models, database contexts, and handling HTTP requests, as well as best practices for building RESTful APIs. Additionally, it covers error handling and model validation in ASP.NET Web API 4.x.

Uploaded by

jeevanshugoel100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Creating a Controller to Retrieve Data in ASP.

NET Core

What is a Web API Controller in ASP.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.

What is a RESTful API?

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.

• Resource-Based: Data is represented as resources, and each resource is identi ed by a


URL.

Steps to Create a Web API Controller to Retrieve Data

1. Create the Model

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) { }

public DbSet<Book> Books { get; set; }


}
}
3. Create the API Controller

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;

public BookController(AppDbContext context)


{
_context = 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.

4. Add the Database Connection in Program.cs


fi
In ASP.NET Core, the DbContext is registered with the dependency injection container in the
Program.cs le.

csharp
CopyEdit
using Microsoft.EntityFrameworkCore;
using OnlineBookStoreAPI.Data;

var builder = WebApplication.CreateBuilder(args);

// Add DbContext service to DI container


builder.Services.AddDbContext<AppDbContext>(options =>

options.UseSqlServer(builder.Configuration.GetConnectionStrin
g("DefaultConnection")));

builder.Services.AddControllers();

var app = builder.Build();

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.

5. Test the API

To test the API, run the application using the command:

bash
CopyEdit
dotnet run
Once the application starts, you can access the API endpoints:

• GET /api/Book: Retrieve a list of all books.

• GET /api/Book/{id}: Retrieve a speci c book by its ID.

You can use Postman or a browser to make GET requests to these endpoints and see the returned
data.

6. Handling Errors and Edge Cases

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.

Building RESTful APIs with ASP.NET Core

1. What is a RESTful API?

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).

2. HTTP Methods for RESTful APIs

• 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).

• PUT: Updates existing data (e.g., update a book’s details).

• DELETE: Deletes data from the server (e.g., remove a book).

3. Status Codes
• 200 OK: Request was successful.

• 201 Created: A resource was successfully created.

• 400 Bad Request: The request was invalid.

• 404 Not Found: The requested resource could not be found.

• 500 Internal Server Error: A server error occurred.

4. Handling Data Serialization

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.

Best Practices for Building RESTful APIs

1. Use HTTP Status Codes Appropriately:

◦ Ensure you use the correct HTTP status codes in responses (e.g., 200 for successful
requests, 404 for not found, etc.).

2. Use Plural Nouns for Resources:

◦ 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.

4. Versioning Your API:

◦ 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.

How Model Validation Works in ASP.NET 4.x

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:

• [Required]: Ensures that the property cannot be null or empty.

• [StringLength]: Speci es the minimum and maximum length of a string property.

• [Range]: Ensures that the value of a numeric property is within a speci ed range.

• [EmailAddress]: Validates whether the property contains a valid email address.

Example: Model with Data Annotations

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.

• The Author property must be between 5 and 100 characters long.

• The Price must be a number between 1 and 1000.

2. Validating the Model in the Controller

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
}

// Proceed with saving the book or further


processing
return Ok("Book added successfully");
}
}
}
• ModelState.IsValid checks if all the validation rules for the model have been
satis ed.

• If the model is invalid, the BadRequest(ModelState) method sends a 400 Bad


Request response with the validation errors.
fi

You might also like