Migrating an ASP.NET MVC project to a .NET Core Web API with Entity Framework Core (EF Core) and Angular
Migrating an ASP.NET MVC project to a .NET Core Web API with Entity Framework Core (EF Core) and Angular involves several key steps. Below is a step-by-step guide to perform the migration effectively:
1. Set Up the .NET Core Web API Project
You need to create a new .NET Core Web API project, which will
replace the MVC controllers and views with API controllers.
Steps:
1.Create a New .NET Core Web API Project:
·
Open Visual Studio or VS Code.
·
Create a new project using the ASP.NET Core
Web API template.
dotnet new webapi -n MyApiProject
·
Choose the correct .NET Core version (e.g.,
.NET 6 or .NET 7).
·
Name the project appropriately.
2. Configure
Routing and Controllers:
In .NET Core, routing for API is based on controllers, typically
inheriting from ControllerBase.
Example:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly
ApplicationDbContext _context;
public
ProductsController(ApplicationDbContext context)
{
_context = context;
}
[HttpGet]
public async
Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await
_context.Products.ToListAsync();
}
[HttpPost]
public async
Task<ActionResult<Product>> CreateProduct(Product product)
{
_context.Products.Add(product);
await
_context.SaveChangesAsync();
return
CreatedAtAction("GetProduct", new { id = product.Id }, product);
}
}
3. Migrate Existing MVC Logic to API:
Migrate the logic from your MVC controllers to API controllers.
Replace the views with data responses (JSON) in your API
controllers.
2. Set Up Entity Framework Core (EF Core)
Add EF Core NuGet Packages: In your Web API project, add the
necessary EF Core packages (if they aren't already installed):
Example:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
2. Create the ApplicationDbContext:
Define your DbContext class to interact with the database.
Example:
public class ApplicationDbContext : DbContext
{
public
ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public
DbSet<Product> Products { get; set; }
// Add other DbSets for
other models
}
3. Configure DbContext in Program.cs or Startup.cs:
In Program.cs (or Startup.cs for older versions), configure the
connection string and add the DbContext to the dependency injection container.
Example:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationDbContext>(options
=>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.MapControllers();
app.Run();
4.Create Database Migrations: Use EF Core migrations to set up
your database.
Example:
dotnet ef migrations add InitialCreate
dotnet ef database update
3. Set Up Angular Front-End
1. Create an Angular Project: If you don’t have an Angular
project, you can create one using the Angular CLI.
Example:
ng new my-angular-app
cd my-angular-app
ng serve
2. Install HTTP Client Module:
In Angular, use the HttpClient module to make HTTP requests to
your Web API.
Import HttpClientModule in app.module.ts:
Example:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations:
[AppComponent],
imports:
[HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule {}
3. Create Angular Services for API Calls: Create a service in
Angular to interact with the Web API.
Example:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private apiUrl =
'http://localhost:5000/api/products'; // API endpoint
constructor(private http:
HttpClient) {}
getProducts():
Observable<Product[]> {
return
this.http.get<Product[]>(this.apiUrl);
}
createProduct(product:
Product): Observable<Product> {
return
this.http.post<Product>(this.apiUrl, product);
}
}
4. Update Angular Components: Update the Angular components to use
the ProductService and display data from the API.
Example Component:
import { Component, OnInit } from '@angular/core';
import { ProductService } from './product.service';
@Component({
selector:
'app-product-list',
templateUrl:
'./product-list.component.html'
})
export class ProductListComponent implements OnInit {
products: any[] = [];
constructor(private
productService: ProductService) {}
ngOnInit() {
this.productService.getProducts().subscribe((data) => {
this.products = data;
});
}
}
4. Handle Authentication and Authorization (Optional)
If your MVC application uses authentication and authorization, you
need to implement it in your Web API and Angular application.
·
Web API: Implement JWT-based authentication in
the Web API using ASP.NET Core Identity or other mechanisms (e.g.,
IdentityServer, OAuth).
·
Angular: Store the JWT token and attach it to
HTTP requests for protected API endpoints.
Example: Authentication in API (using JWT):
public class LoginController : ControllerBase
{
private readonly
IConfiguration _configuration;
private readonly
UserManager<ApplicationUser> _userManager;
private readonly
SignInManager<ApplicationUser> _signInManager;
public LoginController(
IConfiguration
configuration,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_configuration =
configuration;
_userManager =
userManager;
_signInManager =
signInManager;
}
[HttpPost("login")]
public async
Task<IActionResult> Login([FromBody] LoginModel loginModel)
{
var user = await
_userManager.FindByEmailAsync(loginModel.Email);
if (user == null ||
!(await _userManager.CheckPasswordAsync(user, loginModel.Password)))
{
return
Unauthorized();
}
var token =
GenerateJwtToken(user);
return Ok(new {
token });
}
private string
GenerateJwtToken(ApplicationUser user)
{
var claims = new[]
{
new
Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new
Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
var creds = new
SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new
JwtSecurityToken(
issuer:
_configuration["Jwt:Issuer"],
audience:
_configuration["Jwt:Audience"],
claims: claims,
expires:
DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return new
JwtSecurityTokenHandler().WriteToken(token);
}
}
In Angular, store the JWT token and send it with each request to
the API:
Example:
import { HttpHeaders } from '@angular/common/http';
// Add token to headers
const headers = new HttpHeaders().set('Authorization', `Bearer
${your_jwt_token_here}`);
5. Test and Deploy
·
Test the API: Test the Web API endpoints using
tools like Postman or Swagger to ensure they work as expected.
·
Test the Angular Application: Test the Angular
app locally to ensure it can communicate with the Web API.
Deployment:
·
Web API: Deploy the API to Azure, AWS, or your
desired hosting service.
·
Angular: Build and deploy the Angular app
using ng build to create static files and serve them via a web server.
Summary:
Web API: Migrate your MVC controllers to Web API controllers
(using ControllerBase).
EF Core: Set up Entity Framework Core to connect to the database
and migrate your models.
Angular: Set up an Angular project to consume the Web API via
HttpClient.
Authentication: Implement JWT authentication for secure access to
the API if needed.
Deploy: Deploy the Web API and Angular app to the chosen
environment.
By following these steps, you can successfully migrate an ASP.NET
MVC application to a modern .NET Core Web API backend with an Angular frontend,
using EF Core for data access.
Comments
Post a Comment