6- Modern Web Practices in C#: ASP.NET Core with Angular/React and API Development

image 2

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

Welcome back! As a Java developer, diving into modern web practices with C# can open up a world of possibilities. In this post, we’ll cover setting up Angular or React with ASP.NET Core, building Single Page Applications (SPAs), and best practices for API development and testing. We’ll use real-world examples and draw comparisons to Java to make the transition smoother.


1. ASP.NET Core and Angular/React

Combining ASP.NET Core with modern front-end frameworks like Angular or React allows you to build powerful and responsive web applications. This is similar to using Spring Boot with Angular or React in Java.

Setting Up Angular/React with ASP.NET Core

Angular Setup

  1. Create an ASP.NET Core project:
    dotnet new webapi -o MyApi
    cd MyApi
  2. Create an Angular project inside the ASP.NET Core project:
    ng new ClientApp --directory ClientApp
  3. Configure Angular CLI to work with ASP.NET Core:
    Edit Startup.cs to serve the Angular app:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    app.UseSpa(spa =>
    {
    spa.Options.SourcePath = “ClientApp”;
    if (env.IsDevelopment())
    {
    spa.UseAngularCliServer(npmScript: “start”);
    }
    });
    }
    else
    {
    app.UseExceptionHandler(“/Error”);
    app.UseHsts();
    }
    app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }

React Setup

  1. Create an ASP.NET Core project:
    dotnet new webapi -o MyApi
    cd MyApi
  2. Create a React project inside the ASP.NET Core project:
    npx create-react-app ClientApp
  3. Configure React to work with ASP.NET Core:
    Edit Startup.cs to serve the React app:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    app.UseSpa(spa =>
    {
    spa.Options.SourcePath = “ClientApp”;
    if (env.IsDevelopment())
    {
    spa.UseReactDevelopmentServer(npmScript: “start”);
    }
    });
    }
    else
    {
    app.UseExceptionHandler(“/Error”);
    app.UseHsts();
    }
    app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }

Building Single Page Applications (SPAs)

With Angular or React, you can build SPAs that provide a seamless user experience without full page reloads, similar to using frameworks like Angular or React with Spring Boot.

Example Code:

Angular Component:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {
products: any[] = [];

constructor(private http: HttpClient) { }

ngOnInit() {
this.http.get('/api/products').subscribe(data => {
this.products = data as any[];
});
}
}

React Component:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function ProductList() {
const [products, setProducts] = useState([]);

useEffect(() => {
axios.get('/api/products').then(response => {
setProducts(response.data);
});
}, []);

return (
<div>
{products.map(product => (
<div key={product.id}>
{product.name} - ${product.price}
</div>
))}
</div>
);
}

export default ProductList;

2. API Development and Testing

Building robust and well-documented APIs is crucial for modern web development.

REST API Best Practices

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

2- Use appropriate HTTP methods:

GET for retrieving data

POST for creating data

PUT for updating data

DELETE for deleting data

Using Swagger for API Documentation

Swagger is a tool that helps document your APIs, making it easier for developers to understand and test your endpoints. This is similar to using Springfox Swagger in Java.

Setup Swagger in ASP.NET Core:

  1. Install Swagger:dotnet add package Swashbuckle.AspNetCore
  2. Configure Swagger in Startup.cs:
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddControllers();
    services.AddSwaggerGen();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); });
    }

Example Swagger Documentation:

Visit https://localhost:5001/swagger to see the automatically generated API documentation.

Testing APIs

Use tools like Postman or built-in tools in IDEs like Visual Studio to test your APIs. This is similar to using tools like Postman or Insomnia with Java APIs.

Example Test:

  1. Open Postman.
  2. Create a new GET request.
  3. Enter the URL https://localhost:5001/api/products.
  4. Send the request and verify the response.

This guide should help you get started with modern web practices in C# using ASP.NET Core with Angular or React and API development. 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 *