ASP.NET is a free, open-source web application framework developed by Microsoft. It's used to build dynamic websites, web applications, and web services.
You can create an ASP.NET project using:
Example using .NET CLI:
dotnet new webapp -n MyAspNetProject
cd MyAspNetProject
dotnet run
ASP.NET Core is the cross-platform, high-performance evolution of ASP.NET.
The entry point for an ASP.NET Core application:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Configure services and the app's request pipeline:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
ASP.NET Core MVC is a design pattern for achieving separation of concerns.
Routing is the process of matching incoming HTTP requests to controller actions.
Set up in Startup.cs
:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Applied directly to controller actions:
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Action method implementation
}
}
Controllers handle incoming requests and return responses to the client.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[HttpPost]
public IActionResult Contact(ContactViewModel model)
{
if (ModelState.IsValid)
{
// Process the contact form
return RedirectToAction("ThankYou");
}
return View(model);
}
}
Views are responsible for presenting content to the user. Razor is a markup syntax for embedding server-based code into webpages.
@{
ViewData["Title"] = "Home Page";
}
<h1>Welcome to my site, @User.Identity.Name!</h1>
@if (User.IsInRole("Admin"))
{
<p>You are an admin.</p>
}
<ul>
@foreach (var item in Model)
{
<li>@item.Name</li>
}
</ul>
Models represent the data of the application. Data binding is the process of mapping HTTP request data to C# objects.
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(0.01, 1000.00)]
public decimal Price { get; set; }
}
public class ProductController : Controller
{
[HttpPost]
public IActionResult Create(Product product)
{
if (ModelState.IsValid)
{
// Save the product
return RedirectToAction("Index");
}
return View(product);
}
}
Entity Framework Core is an object-relational mapper (ORM) that simplifies data access.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
}
dotnet ef migrations add InitialCreate
dotnet ef database update
public IActionResult Index()
{
var products = _context.Products
.Where(p => p.Price > 10)
.OrderBy(p => p.Name)
.ToList();
return View(products);
}
ASP.NET Core has built-in support for dependency injection.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IProductRepository, ProductRepository>();
services.AddTransient<INotificationService, EmailNotificationService>();
services.AddSingleton<IApplicationCache, MemoryCache>();
}
public class ProductController : Controller
{
private readonly IProductRepository _repository;
public ProductController(IProductRepository repository)
{
_repository = repository;
}
// Controller actions
}
Middleware is software that's assembled into an app pipeline to handle requests and responses.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
ASP.NET Core provides built-in support for authentication and authorization.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseAuthorization();
}
[Authorize]
public class AdminController : Controller
{
[Authorize(Roles = "SuperAdmin")]
public IActionResult SecretOperation()
{
return View();
}
}
ASP.NET Core supports creating RESTful services using Web API.
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _repository;
public ProductsController(IProductRepository repository)
{
_repository = repository;
}
[HttpGet]
public ActionResult<IEnumerable<Product>> GetProducts()
{
return _repository.GetAll().ToList();
}
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = _repository.GetById(id);
if (product == null)
{
return NotFound();
}
return product;
}
[HttpPost]
public ActionResult<Product> PostProduct(Product product)
{
_repository.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}
ASP.NET Core supports unit testing and integration testing.
public class ProductServiceTests
{
[Fact]
public void GetProductById_ReturnsProduct_WhenProductExists()
{
// Arrange
var mockRepository = new Mock<IProductRepository>();
mockRepository.Setup(repo => repo.GetById(1))
.Returns(new Product { Id = 1, Name = "Test Product" });
var productService = new ProductService(mockRepository.Object);
// Act
var result = productService.GetProductById(1);
// Assert
Assert.NotNull(result);
Assert.Equal(1, result.Id);
Assert.Equal("Test Product", result.Name);
}
}
public class ProductControllerIntegrationTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public ProductControllerIntegrationTests(WebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task GetProducts_ReturnsSuccessStatusCode()
{
// Arrange
var client = _factory.CreateClient();
// Act
var response = await client.GetAsync("/api/products");
// Assert
response.EnsureSuccessStatusCode();
}
}
ASP.NET Core applications can be deployed to various platforms.
dotnet publish -c Release
Example of asynchronous programming:
public class ProductController : Controller
{
private readonly IProductService _productService;
public ProductController(IProductService productService)
{
_productService = productService;
}
public async Task<IActionResult> Index()
{
var products = await _productService.GetAllProductsAsync();
return View(products);
}
}
2024 © All rights reserved - buraxta.com