5- Web Development in C#: A Guide for Java Developers

image 2

Play Store Application link – Java to .NET in 9 Steps – App on Google Play

If you’re a Java developer venturing into web development with C#, you’ll find ASP.NET Core to be a powerful framework for building web applications and APIs. This guide will walk you through the basics of ASP.NET Core, including MVC architecture, Razor Pages, Dependency Injection, and building RESTful services. We’ll use real-world examples and draw comparisons to Java for an easier transition.


1. ASP.NET Core Basics

MVC Architecture

ASP.NET Core MVC follows the Model-View-Controller pattern, similar to Spring MVC in Java. This pattern helps separate concerns, making your code more manageable and testable.

  • Model: Represents the data and business logic.
  • View: Displays the user interface.
  • Controller: Handles user input and interacts with the model to return the appropriate view.

Example Code:

// Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

// Controller
public class ProductsController : Controller
{
public IActionResult Index()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M },
new Product { Id = 2, Name = "Phone", Price = 499.99M }
};
return View(products);
}
}

// View (Index.cshtml)
@model List<Product>
@foreach (var product in Model)
{
<p>@product.Name - @product.Price</p>
}

Razor Pages

Razor Pages is a simpler way to build web applications without the need for a controller. It’s similar to JSPs in Java.

Example Code:

@page
@model IndexModel

@{
ViewData["Title"] = "Home page";
}

<h2>@ViewData["Title"]</h2>
<p>Welcome to Razor Pages!</p>

// IndexModel.cs
public class IndexModel : PageModel
{
public void OnGet()
{
}
}

Dependency Injection

ASP.NET Core has built-in support for Dependency Injection (DI), similar to Spring’s DI in Java. This makes it easier to manage dependencies and promote loose coupling.

Example Code:

// Service Interface
public interface IProductService
{
IEnumerable<Product> GetProducts();
}

// Service Implementation
public class ProductService : IProductService
{
public IEnumerable<Product> GetProducts()
{
return new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M },
new Product { Id = 2, Name = "Phone", Price = 499.99M }
};
}
}

// Registering Service
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IProductService, ProductService>();
}

// Using Service in Controller
public class ProductsController : Controller
{
private readonly IProductService _productService;

public ProductsController(IProductService productService)
{
_productService = productService;
}

public IActionResult Index()
{
var products = _productService.GetProducts();
return View(products);
}
}

2. Building RESTful Services

Controllers and Routing

Controllers handle HTTP requests and define routes for your API endpoints. This is similar to Spring MVC’s @RestController and @RequestMapping annotations.

Example Code:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 999.99M },
new Product { Id = 2, Name = "Phone", Price = 499.99M }
};
return Ok(products);
}
}

Models and ViewModels

Models represent the data structure, while ViewModels are used to shape data for the view. This separation is similar to DTOs in Java.

Example Code:

// Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

// ViewModel
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string PriceFormatted => $"${Price:N2}";
}

Action Results and Responses

Action Results in ASP.NET Core control the type of response sent to the client, similar to Java’s ResponseEntity.

Example Code:

[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var product = new Product { Id = id, Name = "Laptop", Price = 999.99M };
if (product == null)
{
return NotFound();
}
return Ok(product);
}

3. Authentication and Authorization

Identity Framework

ASP.NET Core Identity is used for managing user authentication and authorization, similar to Spring Security in Java.

Example Code:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
}

JWT Authentication

JWT (JSON Web Token) authentication is used for securing APIs. This is similar to using JWTs with Spring Security.

Example Code:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
services.AddControllers();
}

Role-Based Access Control

Role-based access control restricts access to parts of your application based on user roles, similar to Spring Security’s role-based authorization.

Example Code:

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}

This guide should help you get started with web development in C# using ASP.NET Core. By leveraging your Java knowledge, you can see how these concepts translate into the C# world, making your learning experience smoother. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *