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

NET Reference Sheet1

The document outlines the steps to create a new ASP.NET Core Web API project, including setting up the solution, adding necessary packages, and configuring routing strategies. It explains conventional and attribute routing, best practices, and the use of ActionResult for handling HTTP responses. Additionally, it discusses the creation and role of models and view models in the MVC pattern, emphasizing their importance in data representation and validation.

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)
4 views8 pages

NET Reference Sheet1

The document outlines the steps to create a new ASP.NET Core Web API project, including setting up the solution, adding necessary packages, and configuring routing strategies. It explains conventional and attribute routing, best practices, and the use of ActionResult for handling HTTP responses. Additionally, it discusses the creation and role of models and view models in the MVC pattern, emphasizing their importance in data representation and validation.

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

1.

dotnet new sln -n SampleProjAPI

2. dotnet new webapi -n SampleProjAPI.API

3. dotnet sln add SampleProjAPI.API/SampleProjAPI.API.csproj

•Creating models, controllers, repo and services folders and their le.

•De ning models -> data -> program.cs -> and app settings .
Adding migration -> updating database.

4.dotnet add package Microsoft.EntityFrameworkCore


//
dotnet add package Pomelo.EntityFrameworkCore.MySql
//mysql provider for ef core.

dotnet add package Microsoft.EntityFrameworkCore.Design


//enable design time services like migrations and sca olding

dotnet add package Swashbuckle.AspNetCore


//for Swagger ui - ui and generator to test api by sending request.

dotnet add package Microsoft.EntityFrameworkCore.Tools


// used for migrating and other things

5. dotnet ef migrations add InitialCreate


dotnet ef database update

6.
dotnet add package Microsoft.AspNetCore.OpenApi --version 8.0.4
dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.0.4
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 8.0.0
dotnet add package Swashbuckle.AspNetCore --version 8.1.0
dotnet add package Microsoft.EntityFrameworkCore --version 8.0.4
fi
ff
fi
Topic: Routing in ASP.NET Core (.NET 6 and above)
Routing is the backbone of how an ASP.NET Core application responds to HTTP requests. It
de nes how incoming URLs are matched to controllers and actions within your Web API or MVC
app.

ASP.NET Core supports two main routing strategies:

1. Conventional Routing
2. Attribute Routing

Let’s break them down with examples and best practices.

🔹 1. Conventional Routing

This pattern-based approach de nes routes centrally, often used in MVC-style apps.

Example: app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/


{id?}");

Explanation:

• {controller=Home} → defaults to HomeController

• {action=Index} → defaults to Index action

• {id?} → optional parameter

Note: This is less common in Web APIs where attribute routing is more explicit and exible.

🔹 2. Attribute Routing

Preferred in Web APIs, attribute routing allows you to de ne routes directly on controllers and
actions using attributes.

Example:

[Route("api/[controller]")] [ApiController] public class BookController : ControllerBase


{ [HttpGet("{id}")] public IActionResult GetBookById(int id) { // logic here }

csharp
CopyEdit
[HttpPost]
public IActionResult AddBook([FromBody] Book book)
{
// logic here
}
}

✨ Key Attributes:
fi
fi
fi
fl
• [Route("api/[controller]")] – sets the base route using the controller name (Book → /api/
book)

• [HttpGet("{id}")] – maps GET requests like /api/book/1

• [HttpPost] – maps POST requests to /api/book

🔹 3. Route Parameters

• Required: [HttpGet("{id}")]

• Optional: [HttpGet("{id?}")]

• With constraints: [HttpGet("{id:int}")] → allows only integer ids

🔹 4. Tokens & Custom Routes

ASP.NET Core allows token replacement for cleaner routes:

• [controller] → Controller class name minus “Controller”

• [action] → Action method name

Example:

[Route("api/[controller]/[action]")] public class ProductsController : ControllerBase { [HttpGet]


public IActionResult List() { ... }

csharp
CopyEdit
[HttpPost]
public IActionResult Create(Product product) { ... }
}

🔹 5. Best Practices

✅ Use Attribute Routing for Web APIs


✅ Follow RESTful naming conventions (e.g., /api/books/by-author)
✅ Add route constraints where appropriate
✅ Version your APIs (e.g., /api/v1/books)
✅ Keep routes lowercase and hyphen-separated

🔹 6. Route Matching Priority

ASP.NET Core uses the most speci c matching route rst.

Example:

[HttpGet("books/{id}")] will be prioritized over [HttpGet("books")]


fi
fi
🔹 7. Minimal APIs in .NET 6+

.NET 6 introduced Minimal APIs where you can de ne routes in Program.cs:

app.MapGet("/api/books/{id}", (int id) => { ... }); app.MapPost("/api/books", (Book book) =>
{ ... });

🔹 8. Route Debugging & Middleware

Routing is enabled through middleware in Program.cs:

app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

🔚 Conclusion

Routing is the bridge between your client requests and the server logic. While conventional routing
works well in MVC, attribute routing is more explicit, exible, and well-suited for APIs.
Understanding route patterns, tokens, parameters, and constraints gives you the power to build
clean, maintainable APIs.

ActionResult and Its Return Types in ASP.NET Core Web API


Introduction

In ASP.NET Core Web API, controller action methods return data to the client. To standardize this
process, ASP.NET Core provides ActionResult and various return types that represent HTTP
responses like 200 OK, 404 Not Found, 400 Bad Request, etc.

What is ActionResult?

ActionResult is a base class de ned in Microsoft.AspNetCore.Mvc namespace.

It represents the result of an action method and can encapsulate both:

• The data returned by the action (like an object)

• The HTTP status code and headers associated with the response

Syntax:

public ActionResult GetItem(int id)

Types of Return Types in ASP.NET Core Web API

1. IActionResult

• This is a general return type for any action that returns an HTTP response.
fi
fi
fl
• It doesn't carry the data directly—only the response structure.

Example:

public IActionResult Get() { return Ok("Success"); }

Common IActionResult Methods:

• Ok(object value) - Returns 200 OK with data

• NotFound() - Returns 404

• BadRequest() - Returns 400

• NoContent() - Returns 204

• Created() - Returns 201

2. ActionResult<T>

• Combines IActionResult + a return type (T)

• Lets you return either a strongly-typed result (like a Book object) or an error response.

Example:

public ActionResult<Book> GetBook(int id) { var book = _dbContext.Books.Find(id); if (book ==


null) return NotFound();

kotlin
CopyEdit
return book; // Implicitly returns Ok(book)
}

Advantages:

• Better API documentation (Swagger knows return type)

• Cleaner syntax with less manual Ok(), NotFound(), etc.

• Supports automatic 200 OK if T is returned directly

3. Speci c Return Types (Not recommended for APIs)

These are rare in Web API but sometimes used:

• string

• JsonResult

• ObjectResult

• ContentResult

Example (Not recommended):


fi
public string Get() { return "Hello"; }

Important HTTP Status Return Methods

Method Description
Ok() 200 OK response
NotFound() 404 Not Found
BadRequest() 400 Bad Request
NoContent() 204 No Content
Created() 201 Created
Unauthorized() 401 Unauthorized
Forbid() 403 Forbidden
Con ict() 409 Con ict
StatusCode(int Custom HTTP
code) status

Conclusion

Use IActionResult if you want full control over the response.

Use ActionResult<T> when returning data and want exibility to also return errors.

For cleaner APIs and Swagger documentation, prefer ActionResult<T>.

Creating a Model in ASP.NET Core MVC

What is a Model?

In ASP.NET Core MVC, a model is a representation of the data used in the application. Models
contain the business logic and validation rules for the application. They interact with the database
and form the structure for the data returned to the views.

How to Create a Model

To create a model, follow these steps:

1. Create a New Class:


◦ Models are typically created as classes.

◦ You can de ne properties that correspond to the data you wish to represent.
fl
fl
fi
fl
2. csharp
CopyEdit

public class Product


3. {
4. public int Id { get; set; }
5. public string Name { get; set; }
6. public decimal Price { get; set; }
7. }
8.

9. Save the Model:


◦ Models are generally saved in a folder named Models for better organization.

10. Usage:
◦ The model can now be used within your controllers to transfer data between your
views and database.

Models in ASP.NET Core MVC Application

Role of Models in MVC Pattern

In the MVC (Model-View-Controller) pattern, the Model acts as the data layer and is responsible
for the following:

• Data Structure: Represents the data structure.

• Data Validation: Contains rules to validate data before being persisted.

• Business Logic: Handles any business rules associated with the data.

Working with Models

• Retrieving Data: Controllers use models to get data from databases or external sources,
perform operations, and pass the data to views.
csharp
CopyEdit

public IActionResult Index()

• {
• var products = _context.Products.ToList();
• return View(products); // Passing model to the view
• }

• Sending Data to Views: Models are passed to views as a parameter.


csharp
CopyEdit

@model IEnumerable<Product> // Defining model type

• @foreach(var product in Model)


• {
• <div>@product.Name</div>
• }

ViewModel in ASP.NET Core MVC Application

What is a ViewModel?

A ViewModel is a special type of model used speci cally for passing data from the controller to the
view. It is often a composite model, combining data from multiple sources to tailor the data needed
for a particular view.

When to Use ViewModels:

• When you need to combine multiple models for a view.

• To avoid overloading views with unnecessary data.

• To structure the data in a way that makes sense for the view, without altering the actual
model.

Example of ViewModel:

csharp
CopyEdit
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
public string Discount { get; set; }
}
fi

You might also like