Unit 4: ASP.
NET Core MVC Authentication and Registration (©2024 MA Lonergan)
Software Development II
SOD316C
UNIT 4
Authentication and Registration in [Link] Core MVC: Part 1
Outcomes: An understanding of
• The MVC Web Application environment in Visual Studio 2022
• Use and work in an existing application to built-in new requirements.
Outcomes applied in the exercise.
• Make changes to the existing solution by using built-in functionality of
EntityFrameworkCore.
• Work with IHttpContextAccessor and IWebHostEnvironment.
• Upload and remove files.
• Meticulously follow instructions.
Prerequisites:
Visual Studio 2022 with the [Link] and web development workload
.NetCore 6
Approach:
1. Download the existing Web Solution folder: ASPNETCore_DB.zip
2. Unzip the file and open the solution in VS2022.
MA Lonergan ©2024 Software Development III 1|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Double click on the [Link] file, see where the database is located.
Click on the Dependencies folder, notice the NuGet packages installed.
Notice from the below image that you are making use of the:
MA Lonergan ©2024 Software Development III 2|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
• EntityFrameworkCore (Data folder => SQLiteDBContext)
• RepositoryPattern (Interfaces, Repositories Folders)
• Model-View-Controller Pattern (Controllers, Models, Views Folder)
Run the solution and click on the Student link:
Test the solution and see if it works. Go through the code in the solution to gain an
understanding of what you are working with.
Modifications to the existing web solution.
As you can see from the above image the student photo does not appear, neither does the
student mail. Double click on the Student Model in the Models folder. You will need to add a
photo and the student email, thus add the following properties:
[Display(Name = "Photo Identicate")]
public string? Photo { get; set; }
[Display(Name = "Contact Mail")]
[Required(ErrorMessage = "Contact Mail")]
public string? Email { get; set; }
Model:
The student model should now reflect as follows in the student model:
MA Lonergan ©2024 Software Development III 3|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
MA Lonergan ©2024 Software Development III 4|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
View:
These additional fields are not yet in Views, unfortunately you will have to do the updates
manually.
Go to Views, double click on the Student folder and open the [Link] file. Add the
following:
• Underneath Enrollment add the following:
Notice the red underline for @WebConstants. WebConstants is a class I created to route
the path of the images.
Right-click on the ASPNETCore_DB project, click add, select class, name the class
WebConstants.
Add the following property:
MA Lonergan ©2024 Software Development III 5|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Go to the wwwroot folder in the project, right-click add a folder named images.
This is the folder that will hold the image of the student photo.
• Double click on Create View and add the following:
MA Lonergan ©2024 Software Development III 6|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
• Next, double click on the [Link] and add the following:
• Next, double click on the [Link] and add the following:
MA Lonergan ©2024 Software Development III 7|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
• Next, double click on the [Link] and add the following:
• Lastly, let’s update the [Link] View:
MA Lonergan ©2024 Software Development III 8|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Database:
Next, we need to update the default data with fake data. Double click on the
[Link] file. Modify the data as follows:
Add the [Link] (available under eThuto) to the images folder under wwwroot.
Next, lets drop the database and re-create the database.
Right-click on Tools => NuGet Package Manager => Package Manager Console
Type in drop-database and press enter.
MA Lonergan ©2024 Software Development III 9|Page
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Enter Y and press enter.
The database has been dropped; you can check this under Database in your project.
Next, double click on the HomeController in the Controllers folder. Scroll to the
SeedDatabase() action method. Uncomment _seednDatabase.Initialize(_context);
Run the solution and click on Database:
It should create and seed the database with the required changes.
MA Lonergan ©2024 Software Development III 10 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Test:
Click on the Students Link:
Modifications almost complete.
Recap:
What did we just do ?
1. Modified the Model
2. Updated the Views
3. Updated the SeedDatabase
4. Dropped the Database
MA Lonergan ©2024 Software Development III 11 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
5. Run the solution
6. Re-create the database
7. View the updated data
You have now updated all the Views with the relevant new properties.
Remember to Comment the _seedDatabase.Initialize(_context); code in the SeedDatabase()
action method in the [Link] file.
Test the solution, add another student with a photo. There will be issues, see to fix it.
StudentController:
These issues relate to the modifications required for uploading and displaying an image.
Thus, we need to modify most of the StudentController’s action methods.
In the StudentController make the following modifications:
Create HttpGet:
[HttpGet]
public IActionResult Create()
{
Student student = new Student();
string fileName = "[Link]";
[Link] = fileName;
return View(student);
MA Lonergan ©2024 Software Development III 12 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Next comes a tricky part.
We are working with uploading an image in the Create HttpPost action method. Have a look
at the next section of code:
Create HttpPost:
[HttpPost]
public IActionResult Create(Student student)
{
var files = [Link];
string webRootPath = _webHostEnvironment.WebRootPath;
string upload = webRootPath + [Link];
string fileName = [Link]().ToString();
string extension = [Link](files[0].FileName);
using (var fileStream = new FileStream([Link](upload, fileName + extension),
[Link]))
{
files[0].CopyTo(fileStream);
}
[Link] = fileName + extension;
try
{
if([Link])
{
_studentRepo.Create(student);
}
catch(Exception ex)
{
throw new Exception("Student record not saved.");
}
return RedirectToAction("Index");
}
We are working with the IHttpContextAccessor and IWebHostEnvironment.
IHttpContextAccessor:
• Gets or sets the current
[Link].
• Returns null if there is no active
[Link].
The HttpContext encapsulates all the information about the individual HTTP request and
response. The HttpContext is accessible by middleware and app frameworks for example
Web API controllers, Razor Pages and so forth. To make use of the HttpContext, you will need
MA Lonergan ©2024 Software Development III 13 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
to add it to the IoC (inversion of control) container, thus enabling you to have access to the
HttpContext for Dependency Injection where you may need it.
Thus, double click on the [Link] file and add the following segment of code:
[Link]<IHttpContextAccessor, HttpContextAccessor>();
This will now add the IHttpContextAccessor to the IoC for DI during Constructor initialization.
Go to the StudentController, and add the IHttpContextAccessor for use.
StudentController Constructor:
private readonly IStudent _studentRepo;
private readonly IHttpContextAccessor _httpContextAccessor;
public StudentController(IStudent studentRepo, IHttpContextAccessor httpContextAccessor)
{
try
{
_studentRepo = studentRepo;
_httpContextAccessor = httpContextAccessor;
}
catch (Exception ex)
{
throw new Exception("Constructor not initialized - IStudent studentRepo");
}
}
Next, we need to add the IWebHostEnvironment.
MA Lonergan ©2024 Software Development III 14 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Notice the content of IWebHostEnvironment:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using [Link];
using [Link];
namespace [Link]
{
/// <summary>
/// Provides information about the web hosting environment an application is running in.
/// </summary>
public interface IWebHostEnvironment : IHostEnvironment
{
/// <summary>
/// Gets or sets the absolute path to the directory that contains the web-servable
application content files.
/// </summary>
string WebRootPath { get; set; }
/// <summary>
/// Gets or sets an <see cref="IFileProvider"/> pointing at <see cref="WebRootPath"/>.
/// </summary>
IFileProvider WebRootFileProvider { get; set; }
}
}
It is directly related to the [Link](); middleware, thus make the following
modifications to the StudentController.
StudentController Constructor:
private readonly IStudent _studentRepo;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWebHostEnvironment _webHostEnvironment;
public StudentController(IStudent studentRepo, IHttpContextAccessor httpContextAccessor,
IWebHostEnvironment webHostEnvironment)
{
try
{
_studentRepo = studentRepo;
_httpContextAccessor = httpContextAccessor;
_webHostEnvironment = webHostEnvironment;
}
catch (Exception ex)
{
throw new Exception("Constructor not initialized - IStudent studentRepo");
}
These modifications will now allow for the changes in the Create HttpPost action method to
take effect. Add the code as given previously (under Create HttpPost) , run the solution and
test.
MA Lonergan ©2024 Software Development III 15 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
MA Lonergan ©2024 Software Development III 16 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
The result on the Index page should be as follows:
Check the database to view the record:
Check the images folder to view the image:
Click on the Details link in the Index page:
MA Lonergan ©2024 Software Development III 17 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
The Student detail should appear.
Next, we look at Edit. This is also a bit tricky. You can keep the Edit HttpGet as is, however
the Edit HttpPost must be modified as follows:
MA Lonergan ©2024 Software Development III 18 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Edit HttpPost:
if ([Link] > 0)
{
var files = [Link];
string webRootPath = _webHostEnvironment.WebRootPath;
string upload = webRootPath + [Link];
string fileName = [Link]().ToString();
string extension = [Link](files[0].FileName);
var oldFile = [Link](upload, photoName);
if ([Link](oldFile))
{
[Link](oldFile);
}
using (var fileStream = new FileStream([Link](upload, fileName + extension),
[Link]))
{
files[0].CopyTo(fileStream);
}
[Link] = fileName + extension;
}
else
{
[Link] = photoName;
}
try
{
_studentRepo.Edit(student);
}
catch (Exception ex)
{
throw new Exception("Student record not saved.");
}
return RedirectToAction("Index");
What it means, if there is a file in the [Link], then delete the old file and upload
the new file.
Basically, that’s what’s happening. Further, notice that you are pulling the photoName from
the request form, to identify the old file name. Investigate the [Link] file to identify how
this is done. It is set as a hidden field when the cshtml is populated with data.
MA Lonergan ©2024 Software Development III 19 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
Remember to add enctype=”multipart/form-data” to the Edit form asp-action.
Run the solution, modify any one of the records by editing the image.
Click save.
MA Lonergan ©2024 Software Development III 20 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
The Index list should display as follows:
You may click on Details to View the Detail of the Student.
Click on the Delete link and Delete the Student information, the Index form should look as
follows:
Done with the modifications.
The purpose of this exercise was to teach you how intricate it can be to make modifications
to an already existing application. Further, how one thing affects another thing and that it
takes some investigation to modify applications. You need to know what you are doing and
where you are going by making modifications. Thus, planning is crucial in writing software
solutions, making modifications can be time consuming and complicated, but it is part of
writing software.
MA Lonergan ©2024 Software Development III 21 | P a g e
Unit 4: [Link] Core MVC Authentication and Registration (©2024 MA Lonergan)
In the next tutorial, we will make use of the built-in Authentication and Registration of
[Link] Core MVC, to register a user. We will make use of the current solution, thus make
sure your copy works.
MA Lonergan ©2024 Software Development III 22 | P a g e