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 :: ASP.NET MVC Folder And File Structure

clock September 26, 2025 09:03 by author Peter

When we establish a new ASP.NET MVC application, I'll go over the automatically generated ASP.NET MVC Folder and File Structure. Because of the separation of concerns (codes) and folder structure, the ASP.NET MVC framework has grown in popularity among developers in recent years. Understanding the purpose and necessity of every folder and file in an ASP.NET MVC application is crucial for developers.

What is the separation of concerns in ASP.NET MVC?
It is a process of breaking the program into various distinct features which overlap in functionality as little as possible. MVC pattern focuses on separating the content from presentation and data-processing from the content. Let's understand it with an example.
 
Step 1
Open Visual Studio 2015 or a version of your choice and create a new project.
 
Step 2
Choose the "web application" type for the project and give an appropriate name to your project.

Step 3 
Select MVC template below and click OK.

Step 4
Check the auto-generated folder and file structure of the created project.

Let’s start discussing the use and need of each Folder and File of an MVC application in details one by one.
 
App_Data
The App_Data folder of MVC application is used to contain the application related data files like .mdf files, LocalDB, and XML files, etc. The most important point that you need to remember is that IIS is never going to serve files from this App_Data folder.
 
App_Start
The App_Start folder of MVC application is used to contain the class files which are needed to be executed at the time the application starts. The classes like BundleConfig, FilterConfig, IdentityConfig, RouteConfig, and Startup.Auth etc. are stored within this folder. So, in simple words, we can say that configuration related class files are stored in App_Start.

Content
The Content folder of an MVC application is used to store the static files such as the image files, CSS files, and icons files. When we create an MVC 5 application, by default the bootstrap.css, bootstrap.min.css, and Site.css files are included by Visual Studio, as shown in the image below.

Controllers
The Controllers folder in MVC application is used to contain all the controllers of your application. The Controller is basically a class which is inherited from the base Controller class. The name of the Controller should end with the word Controller. It is the class which actually handles the user’s request and returns a response.

Fonts
The Fonts folder of an MVC application contains the custom font files that are required for the application.

Models
The Models folder of an MVC application is used to store the class files which are used to store the domain data as well as business logic to manage the data.
 
Scripts
The Scripts folder of MVC application is used to contain all the JavaScript files that are required for the application. When we create an MVC 5 application, by default the necessary JavaScript files for jQuery and bootstrap are included. If you want to create any custom JavaScript files then it should be created within this folder or any subfolder of this folder. This is not mandatory but it is a good programming practice as at a later time you can easily find out the JavaScript files.

Views
The Views Folder of an MVC application is used to contain the .cshtml files for the application. In MVC, the .cshtml file is a file where we need to write the HTML code along with the C# code. The Views folder in MVC applications includes separate folders for each and every controller for your application. For example, all the .cshtml files of the HomeController will be in the View => Home folder.
 
We also have the Shared folder under Views folder. The Shared Folder in MVC is used to contain all the views which are needed to be shared by different controllers e.g. error files, layout files, etc.

Now, let us discuss the configuration files which are created by the framework by default
 
Global.asax
The Global.asax file in an MVC application allows us to write code which we want to run at the application level, such as Application_BeginRequest, Application_error, Application_Start, session_start, session_end, etc.
 
Packages.config
The Packages.config file in MVC application is managed by the NuGet which will keep track of what packages and versions have installed within your application.
 
Web.config 
The Web.config file of an MVC application is one of the most useful and important files which contains the application level configurations.
 
Summary
In this article, we discussed the ASP.NET MVC Folder and File structure. Once you understand the need and use of each folder and file of an MVC application, it is easy for you to find, store, and organize the project related files.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Use EF Core to Connect ASP.NET Core MVC to a Database (DB-First)?

clock September 17, 2025 08:46 by author Peter

Studying Database +.NET It may feel like you're trying to connect your phone charger into the incorrect socket for the first time. It's very simple once you know where the plug goes, so don't worry. This article will teach you how to use Entity Framework Core (DB-First method) to link an ASP.NET Core MVC application to a SQL Server database. Consider it similar to placing an online food order:The Database is the restaurant, EF Core is the Swiggy/Zomato delivery guy, Your App just places the order and waits for the food (data) to arrive


By the end, you'll have a simple working app that talks to your database .

If you want to learn about EF Core, please read the full article at Understanding Entity Framework in .NET

Getting Started with ASP. NET Core MVC + Database-First Approach
So you've just installed Visual Studio and are staring at that "New Project" dialog, thinking:
"How do I make this thing talk to my database… without blowing it up?"

Don't worry. Today, we'll learn DB-First with Entity Framework Core step by step. Think of EF Core as your Uber driver for data:

You don't drive directly to the SQL Server.

You just tell EF Core your pickup point (connection string) and drop-off (models).

It does the heavy lifting.

Step 1. Create / Open an ASP.NET Core MVC Project

Open Visual Studio ---> New Project .NET Core Web App (Model-View-Controller).

Quick refresher on MVC:

  • Model → Our data (like Student, Subject).
  • View → The webpage (HTML, CSS).
  • Controller → The middleman who listens to clicks and fetches data.

Real-world analogy:
Model = Ingredients
Controller = Chef
View = The delicious dish

Step 2. Install Required NuGet Packages

Open Package Manager Console (or terminal).

  • dotnet add package Microsoft.EntityFrameworkCore
  • dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  • dotnet add package Microsoft.EntityFrameworkCore.Tools
  • dotnet add package Microsoft.EntityFrameworkCore.Design

When we set up database connections in .NET, we need a few special packages. EntityFrameworkCore is like the brain of the system that knows how to manage data. SqlServer acts as the translator, helping our app talk clearly with SQL Server. Tools provides us with the scaffold command, making life easier when we need to generate models from our database. And Design allows Visual Studio to work smoothly with EF Core. Without these, our project is like a car without wheels .it looks fancy, but it just won’t move!

Step 3. Scaffold Models + DbContext from Existing Database

The scaffold command reverse-engineers an existing database and generates two things for us automatically:
Entity classes (one class per table — e.g., Student.cs with properties that map to table columns.

A DbContext class (e.g., ResultDbContext that contains DbSet<T> properties and OnModelCreating mapping code.

In short: it turns the database schema into C# classes so we can use LINQ and DbContext instead of hand-writing raw SQL.

Before we run the command, make sure:

  • The project builds successfully (scaffolding reads the project & its packages).
  • If the project is broken, the scaffold will likely fail. We have the needed NuGet packages in the project

Now comes the magic command (run at project root):
dotnet ef dbcontext scaffold
"Server=Micheal\SQLEXPRESS;Database=ResultManagement;Trusted_Connection=True;TrustServerCertificate=True;"
Microsoft.EntityFrameworkCore.SqlServer -o Datamodel -c ResultDbContext


What’s happening here:
"Server=.;Database=...;" Database address.

Microsoft.EntityFrameworkCore.SqlServer Provider.
-o Datamodel → Place generated classes inside the Datamodel folder.
-c ResultDbContextName of our DbContext class (we could call it MyUberDb if we like).


Result
EF Core creates classes for each table (e.g., Student.cs, Subject.cs).
And one DbContext (like ResultDbContext.cs).

Think of DbContext as our database remote control. Instead of writing SQL manually, we now say:
_db.Students.ToList();

EF Core silently goes behind the scenes, “SELECT * FROM Students”.

Step 4. Register DbContext in Program.cs

Before our application runs, we need to register our database context with the Dependency Injection (DI) container in Program.cs.
Add this before var app = builder.Build();:

builder.Services.AddDbContext<ResultDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


Why must it go before app.Build() and app.Run():
All services (like DbContext) must be registered before the app is built.

If we place it after app.Run(), the app has already started; it won’t know how to inject ResultDbContext, leading to runtime errors like:
“Unable to resolve service for type 'ResultDbContext'...”

Why We Use AddDbContext in Program.cs
builder.Services.AddDbContext<ResultDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));


This does three important things:
Registers ResultDbContext with the DI container

Tells .NET how to create and manage instances of ResultDbContext.

Configures EF Core to use SQL Server
The UseSqlServer(...) method sets up the provider and connection string it tells EF Core where and how to connect to the database.

Keeps configuration clean and reusable

Using builder.Configuration.GetConnectionString("DefaultConnection") Let's change the connection string without touching your code.

In simple terms

AddDbContext tells .NET: “Here’s the database I want to use, and here’s how to connect to it.”

Once registered, anytime our code (like a controller) needs to interact with the database, .NET will automatically inject the configured ResultDbContext.

Why We Store the Connection String in appsettings.json?

"ConnectionStrings": {
"DefaultConnection": "Server=Micheal\\SQLEXPRESS;Database=ResultManagement;Trusted_Connection=True;TrustServerCertificate=True;"
}


Advantages

  • Separation of concerns: Keeps config data separate from code.
  • Easy environment switching: You can use different connection strings for Development, Testing, and Production.
  • Security: Avoids hardcoding sensitive data (like usernames or passwords) directly in Program.cs.
  • It’s like not writing your credit card PIN directly on the card better security and flexibility.

Conclusion
In this Article, we explored how to connect an .NET Core MVC app to SQL Server using EF Core (DB-First approach). By using EF Core, we avoided writing raw SQL and instead used LINQ to query our database in a clean and maintainable way. DB-First is especially powerful when a database already exists. It helps us integrate smoothly and build web apps faster. With the database connection in place, our next step is to create Controllers and Views to perform CRUD operations (Create, Read, Update, Delete), turning our project into a fully functional app.

Remember: DbContext is our remote control, and EF Core is the Uber driver that fetches data for us.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Handling Secure File Uploads in ASP.NET Core MVC

clock September 9, 2025 07:33 by author Peter

Uploading files is a standard feature of contemporary web apps. Users often require this capability for submitting documents or posting a profile picture. Here's the catch, though. An enormous security risk might arise from improper file upload management. Attackers may try route traversal, upload malicious files, or even launch denial-of-service attacks.

ASP.NET Core MVC secure file upload handling will be covered in this post along with best practices, sample code, and detailed instructions.

Why Is File Upload Security Important?
Insecure file uploads can lead to:

  • Malware Upload: Hackers upload .exe,.js files disguised as images.
  • Path Traversal: Using filenames like ../../web.config to overwrite sensitive files.
  • Denial of Service (DoS): Uploading very large files to exhaust server resources.
  • MIME Type Spoofing: Uploading dangerous files renamed as .jpg or .png.
  • Unauthorized Access: Files stored in wwwroot are directly accessible via URL.

Therefore, a multi-layered defense is critical.

Best Practices for Secure File Uploads
Here are the golden rules for handling file uploads in ASP.NET Core MVC:

  • Limit File Size: Prevent oversized uploads.
  • Restrict File Types: Allow only specific file extensions.
  • Use Safe Filenames: Never trust user-supplied filenames.
  • Store Outside wwwroot: Prevent direct public access.
  • Validate File Content: Don’t rely solely on extensions.
  • Scan Files (Optional): Use antivirus or third-party scanning APIs.
  • Use HTTPS: Ensure secure transport during upload.

Step-by-Step Implementation in ASP.NET Core MVC

Let’s implement secure file upload handling.

Step 1: Configure Maximum File Size
In Program.cs, set the maximum upload size:
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 10 * 1024 * 1024; // 10 MB limit
});

var app = builder.Build();
app.Run();


Step 2: Create the Upload Model
using System.ComponentModel.DataAnnotations;

public class FileUploadViewModel
{
    [Required]
    public IFormFile File { get; set; }
}

Step 3: Create the Controller

using Microsoft.AspNetCore.Mvc;

public class FileUploadController : Controller
{
    private readonly long _fileSizeLimit = 10 * 1024 * 1024; // 10 MB
    private readonly string[] _permittedExtensions = { ".jpg", ".png", ".pdf" };
    private readonly string _targetFilePath;

    public FileUploadController(IWebHostEnvironment env)
    {
        // Store files securely outside wwwroot
        _targetFilePath = Path.Combine(env.ContentRootPath, "SecureUploads");
        if (!Directory.Exists(_targetFilePath))
        {
            Directory.CreateDirectory(_targetFilePath);
        }
    }

    [HttpGet]
    public IActionResult Index() => View();

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Upload(FileUploadViewModel model)
    {
        if (model.File == null || model.File.Length == 0)
        {
            ModelState.AddModelError("File", "Please select a file.");
            return View("Index");
        }

        //  Validate file size
        if (model.File.Length > _fileSizeLimit)
        {
            ModelState.AddModelError("File", "File size exceeds the limit.");
            return View("Index");
        }

        // Validate extension
        var ext = Path.GetExtension(model.File.FileName).ToLowerInvariant();
        if (string.IsNullOrEmpty(ext) || !_permittedExtensions.Contains(ext))
        {
            ModelState.AddModelError("File", "Invalid file type.");
            return View("Index");
        }

        // Generate safe filename
        var trustedFileName = Path.GetRandomFileName() + ext;
        var filePath = Path.Combine(_targetFilePath, trustedFileName);

        // Save securely
        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await model.File.CopyToAsync(stream);
        }

        ViewBag.Message = "File uploaded successfully!";
        return View("Index");
    }
}


Step 4: Create the Razor View
@model FileUploadViewModel

<h2>Secure File Upload in ASP.NET Core MVC</h2>

<form asp-action="Upload" method="post" enctype="multipart/form-data">
    <div>
        <input type="file" asp-for="File" />
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
    <button type="submit">Upload</button>
</form>

@if (ViewBag.Message != null)
{
    <div class="alert alert-success">@ViewBag.Message</div>
}


Additional Security Enhancements

  • Validate File Signature (Magic Numbers)
    • Instead of trusting extensions, check file headers.
  • Quarantine Uploads
    • Save files temporarily before scanning.
  • Logging & Monitoring
    • Log all uploads for auditing.
  • Rate Limiting
    • Prevent abuse from excessive uploads.

Conclusion
Secure file upload handling in ASP.NET Core MVC requires layered security:

  • Restrict file size and types
  • Validate extensions & MIME type
  • Store outside. wwwroot
  • Use safe filenames

You can provide reliable and secure upload capabilities in your ASP.NET Core MVC applications by adhering to these guidelines.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Preventing SQL Injection in ASP.NET MVC, ASP.NET Core MVC, and Web API Applications?

clock September 1, 2025 09:37 by author Peter

SQL Injection (SQLi) is one of the most dangerous and common vulnerabilities in web applications. It allows attackers to manipulate queries executed by your database, potentially leading to unauthorized data access, modification, or even complete database takeover. As developers, it is our responsibility to ensure that applications are secure against such attacks. In this article, we will explore practical strategies and C# code examples to prevent SQL Injection in ASP.NET MVC , ASP.NET Core MVC , and Web API applications.

What Is SQL Injection?
SQL injection happens when user input is directly concatenated into SQL statements without proper sanitization or parameterization.

Vulnerable code:
string sql = "SELECT * FROM Users WHERE Username = '" + username + "'";

If an attacker enters '; DROP TABLE Users; -- , the query becomes destructive and can delete your table.

Best Practices To Prevent SQL Injection
1. Always Use Parameterized Queries

The golden rule : never concatenate user input directly into SQL . Use parameters instead.

Secure Example (ADO.NET)

public User GetUserByName(string username)
{
    const string sql = "SELECT Id, Username, Email FROM Users WHERE Username = @Username";
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, conn))
    {
        cmd.Parameters.Add(new SqlParameter("@Username", SqlDbType.NVarChar, 256)
        {
            Value = username ?? (object)DBNull.Value
        });

        conn.Open();
        using (var reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                return new User
                {
                    Id = reader.GetInt32(0),
                    Username = reader.GetString(1),
                    Email = reader.GetString(2)
                };
            }
        }
    }
    return null;
}


2. Use ORM Safely (Entity Framework Core)

LINQ queries are safe by default:
var user = await _dbContext.Users
    .Where(u => u.UserName == username)
    .FirstOrDefaultAsync();


Unsafe (don’t do this):
var sql = $"SELECT * FROM Users WHERE UserName = '{username}'";
var users = _dbContext.Users.FromSqlRaw(sql).ToList();


Safe (use parameters):
var users = _dbContext.Users
    .FromSqlInterpolated($"SELECT * FROM Users WHERE UserName = {username}")
    .ToList();


3. Stored Procedures With Parameters

Stored procedures can be safe if you avoid dynamic SQL inside them.

Secure Example:
using (var cmd = new SqlCommand("usp_GetUserById", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int) { Value = userId });
}

Avoid this inside SP:
EXEC('SELECT * FROM Users WHERE Username = ' + @UserName)


4. Dapper (Micro ORM)

Dapper parameterizes queries by default.

Secure Example:
var user = conn.QuerySingleOrDefault<User>(
"SELECT * FROM Users WHERE Username = @Username",
new { Username = username });

C#

Unsafe (don’t do this):

var user = conn.QuerySingleOrDefault<User>(
$"SELECT * FROM Users WHERE Username = '{username}'");


5. Validate and Whitelist Inputs

  • Use length checks (e.g., max 256 chars for username).
  • Use type checks (ensure integers are integers).
  • Use whitelists for sorting, filtering, or selecting columns.

Whitelist Example:
private string GetOrderBy(string sort)
{
    return sort switch
    {
        "name" => "Name",
        "date" => "CreatedDate",
        _ => "Id"
    };
}

C#
6. Example: ASP.NET Core Web API Controller

[HttpGet("search")]
public async Task<IActionResult> Search([FromQuery] string q)
{
    if (string.IsNullOrWhiteSpace(q)) return BadRequest("Search term required");

    var users = await _dbContext.Users
        .Where(u => EF.Functions.Like(u.UserName, $"%{q}%"))
        .ToListAsync();

    return Ok(users);
}

Quick Checklist

  • Never concatenate user input into SQL.
  • Always use parameters in ADO.NET, EF, or Dapper.
  • Validate input length, type, and format.
  • Use whitelists for dynamic columns (e.g., sorting).
  • Apply the least-privilege principle to the DB account.
  • Log suspicious queries and monitor for attacks.
  • Regularly update dependencies and apply DB patches.

Conclusion
SQL injection remains a critical security risk , but by following best practices—parameterized queries, ORM safe usage, validation, stored procedures, and least privilege —you can protect your ASP.NET MVC, ASP.NET Core MVC, and Web API applications from this threat. Security is not a one-time task but a continuous process . Always review your code, test for vulnerabilities, and apply secure coding standards across your team.



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