European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: Customer Error page In MVC 5.0

clock January 23, 2025 07:44 by author Peter

In this article, we will look at how to manually customize an error page in ASP.NET MVC 5.


MVC Introduction
The MVC architectural pattern separates the user interface (UI) of an application into three main parts.

Model
A set of classes that describes the data you are working with as well as the business logic.

View
Defines how the application’s UI will be displayed. It is pure HTML, which decides how the UI is going to look.

Controller
A set of classes that handles communication from the user, overall application flow, and application-specific logic

When an HTTP request arrives for an MVC application, that request gets routed to a controller, and then it is up to the controller to talk to either the database, the file system, or the model.

Why do we need a Custom Error Page?
We would just configure our custom error pages in one place and it would just work, no matter how/where the error was raised. In order to handle exceptions thrown by your action methods, you need to mark your method with the HandleError attribute. The HandleError attribute also allows you to use a custom page for this error.

Steps to be Followed
Step 1

Create a MVC application named “Http500Test”.

The solution looks like this

Step 2
Create a Controller class file named “CustomerErrorUserController.cs”

[HandleError] attribute provided built-in exception filters. This attribute can be applied over the action method as well as the controller or at the global level.

At CustomerErrorUser/Index, this application will show error.cshtml as the view not found in Index but in the web.config file. The error statusCode="404" means that the file is not found and it means the controller name or controller action method name is the issue.

[HandleError] //If I put in this attribute and run, it will go to the Customized by a Default error page.

Step 3
Create a controller class named “ErrorController.cs”

I have added two action methods – NotFound() and UnhandledException().

Step 4
Go to View/Shared Folder; create two views named “NotFound.cshtml” and “UnhandledException.cshtml”

Put your own code in the NotFound.cshtml file by removing the existing code.

Put your own code in the UnhandledException.cshtml file by removing the existing code.

Step 5
Go to Web.config and. Add some code for “File Not Found” and “UnhandledException”

Output
http://localhost:63217/CustomeErrorUser

How to display UnhandledException?
I have added two lines of code in the About() action method in HomeController.cs

Now run this MVC app and click on “About”

Output

Instead of redirecting to “UnhandledException.cshtml”, the app is showing error.cshtml file

How to show UnhandledException.cshtml?
Visual Studio, by default, is creating two cshtml files, i.e. _Layout.cshtml and Error.cshtml inside the Shared folder.
Since we are using [HanldeError] attribute, all the unhandled exceptions will be redirected to by default error page (Error.cshtml).
There was some boilerplate code left in the FilterConfig.cs when creating the project.

This creates a new instance of HandleErrorAttribute, which is applied globally to all of my views. With no customization, if a view throws an error while utilizing this attribute, MVC will display the default Error.cshtml file in the Shared folder.

Commenting this line out solved the problem and allowed me to use custom error pages for 500 errors.

Again run the application and click on “About”

Thank you so much for watching the article. I hope this will be helpful. Please provide your comments in the box below.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Optimize Relationships Migrations Performance in ASP.NET Core MVC

clock January 7, 2025 06:36 by author Peter

Database relationships, migrations, and performance optimization must all be carefully considered when creating scalable and effective ASP.NET Core MVC apps. These topics are thoroughly covered in this essay, which also walks you through implementation techniques and best practices.

Managing Relationships in ASP.NET Core MVC
Entity Framework Core (EF Core) simplifies defining and managing relationships in your database. Understanding and implementing relationships effectively ensures data integrity and simplifies querying related data.

One-to-One Relationship
In a one-to-one relationship, one entity is associated with exactly one other entity.

Entity Classes

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public UserProfile Profile { get; set; }
}

public class UserProfile
{
    public int Id { get; set; }
    public string Bio { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
}

Configuration in DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .HasOne(u => u.Profile)
        .WithOne(p => p.User)
        .HasForeignKey<UserProfile>(p => p.UserId);
}

One-to-Many Relationship
In a one-to-many relationship, one entity is related to many others.

Entity Classes
public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public Author Author { get; set; }
}

Configuration
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Author>()
        .HasMany(a => a.Books)
        .WithOne(b => b.Author)
        .HasForeignKey(b => b.AuthorId);
}

Many-to-Many Relationship

EF Core 5.0+ supports many-to-many relationships without requiring a joint entity.

Entity Classes
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int Id { get; set; }
    public string Title { get; set; }
    public ICollection<Student> Students { get; set; }
}

EF Core Automatically Creates a Join Table

No additional configuration is required for basic many-to-many relationships.

Migrations in ASP.NET Core MVC

Migrations are essential for evolving your database schema over time while maintaining data integrity.

Creating and Applying Migrations

Add a migration
dotnet ef migrations add InitialCreate

Apply the migration
dotnet ef database update

Updating Migrations
When do you modify your entity models?

Add a new migration
dotnet ef migrations add UpdateSchema

Apply the migration
dotnet ef database update

Rolling Back Migrations
To revert to a previous migration.
dotnet ef database update PreviousMigrationName

Seeding Data
Seed data in the OnModelCreating method to populate initial data.

Example
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Author>().HasData(
        new Author { Id = 1, Name = "Peter Scott" },
        new Author { Id = 2, Name = "Michael Scott" }
    );
}

Run the migrations to apply the seed data.

Performance Optimization

Optimizing performance ensures scalability and a better user experience. Below are strategies for improving performance in ASP.NET Core MVC.

Query Optimization
Use AsNoTracking for read-only queries
var books = _context.Books.AsNoTracking().ToList();

Use Eager Loading to fetch related data
var author = _context.Authors.Include(a => a.Books).FirstOrDefault(a => a.Id == id);

Indexing
Define indexes on frequently queried columns to improve performance.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>()
        .HasIndex(b => b.Title)
        .HasDatabaseName("Index_Title");
}


Caching

Use caching to store frequently accessed data.

MemoryCache
services.AddMemoryCache();

if (!_cache.TryGetValue("Books", out List<Book> books))
{
    books = _context.Books.ToList();
    _cache.Set("Books", books, TimeSpan.FromMinutes(5));
}

Pagination
Fetch data in chunks using Skip and Take.
var books = _context.Books
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToList();


Database Connection Pooling
Enable connection pooling in the connection string.
"ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=True;Pooling=true;"
}

Profiling Tools
Use profiling tools like MiniProfiler to identify performance bottlenecks.
dotnet add package MiniProfiler.AspNetCore.Mvc

Monitoring and Diagnostics

  • Application Insights: monitor application performance in production.
  • Logging: Implement structured logging using libraries like Serilog or NLog.

Conclusion
Managing relationships, migrations, and optimizing performance in ASP.NET Core MVC is crucial for building scalable, maintainable, and efficient applications. By leveraging EF Core for relationships, employing robust migration strategies, and implementing performance best practices, developers can create applications that are both performant and easy to maintain.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in