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 Core MVC Areas

clock July 25, 2025 08:57 by author Peter

One of ASP.net MVC's lovely features is Area, which lets you arrange related functionality together. For the functional or business component's physical grouping, we can establish a hierarchy. Stated differently, an area is a smaller functional unit that possesses a unique collection of controllers, views, and models. One or more areas may be present in ASP.net MVC applications. Therefore, we can use Areas to break up our large application into more manageable functional groups. The MVC framework employs naming conventions to establish relationships between the logical components, which include the Model, View, and Controller. These components are stored in distinct directories.

Controllers and Views are used to arrange everything in MVC applications. Typically, the first part of our URL is determined by the controller name, and the second part is the action name. Rendering views by default have the same name as the action method. Area creation in older ASp.net MVC applications is quite simple. Defaul offers the ability to create an area by selecting "Add >> Area" with a right-click on the project. The template automatically creates the area folder and its contents.

How to create "Area" in ASP.net Core?
As we are aware, there is no option to create area by right clicking on project folder. So if we want to create area in Asp.net Core MVC application, Create new folder and name it to area. Within this folder we can create another new folder and give it to any logical name. Here we need to Model, View and Controller folder manually. To demonstrate the example, I have created folder "Test" under "Areas" folder and within this folder I have create three folders: Models, Views and Controllers.

At the time of rendering the view, by Default MVC tries to find out the views within an Area. If it is not found, it tries in other locations. Following are the locations in which MVC tries to find view.
    /Areas/<Area Name>/Views/<Controller Name>/<Action Name>.cshtml  
    /Areas/<Area Name>/Views/Shared/<Action Name>.cshtml  
    /Views/Shared/<Action Name>.cshtml  


These default locations can be changed using AreaViewLocationFormats of RazorViewEngineOptions. In this example, I have given name of the folder as "Areas", but it can be anything. It is not necessary that area folder name needs to be "Areas". This can be changed using MVC option.
 
In this structure, only View folder is in consideration becausethe rest of the content like controllers and models are the classes and it can be compiled within single dll whereas the content of views is compiled individually.
 
Once we have defined the folder hierarchy, we have to tell MVC which controller is associated with which area. We can do this thing by decorating controller with "Area" attribute.
    namespace AreasExample.Areas.Test.Controllers  
    {  
        using Microsoft.AspNetCore.Mvc;  
        [Area("Test")]  
        public class HomeController : Controller  
        {  
            public IActionResult Index()  
            {  
                return View();  
            }  
         }  
    }  

Next step is to setup a route definition which work with our newly created areas. To demonstrate the example, I have use a conventional route that define in "Configure" method of Startup class.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
    {  
        app.UseStaticFiles();  
      
        app.UseMvc(routes =>  
        {  
            routes.MapRoute(  
                name: "areaRoute",  
                template: "{area:exists}/{controller=Home}/{action=Index}");  
      
            routes.MapRoute(  
                name: "default",  
                template: "{controller=Home}/{action=Index}/{id?}");  
        });  
    }  


The views under our area do not share the _ViewImports.cshtml and _ViewStart.cshtml. This means that layout page of our site will not apply automatically to the views under Areas. To apply common layout page that is located at root Views folder to our views under area, we need to copy both files _ViewImports.cshtml and _ViewStart.cshtml to view folder of each area. The _ViewStart.cshtml file contain the location of the layout page, so we need to correct layout page path after coping the file.
_ViewStart.cshtml
    @{  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }  


Generating links from an action
Generating links from an action method (which controller is under area) to another action on different controller and different area, we need to pass area name with route argument.
    @Html.ActionLink("Go to Home Page of Test Area“, "Index", "Home", new { area = "Test" })   

We can also generating the link for the action (which controller is under area) to another action on different controller which is not under any area by passing blank area value to the route argument.
    @Html.ActionLink("Go to Home Page", "Index", "Home", new { area = "" }) 

Output

Summary
Areas in asp.net core MVC provide the following features,

  • Application may have one or more area
  • Every area has its own Model and View Controller
  • It allows us to organize large MVC applications into multiple components which work independently
  • We can have same name controller within different areas

Currently nested areas (areas within area) are not directly supported by Asp.net core application but it can be done using IViewLocationExpander. It's used to modify view locations and how the view engine searches for the path.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Set Up Server Environment For ASP.NET MVC Application On Development Machine

clock July 11, 2025 10:37 by author Peter

This article explains how to configure the local development machine's server environment for an ASP.NET MVC application. Because a web application runs on a server that end users can access, it is best practice to create the application in the same live environment on a local system to avoid making further changes when it goes live. One of the two web servers may be hosted and tested by an MVC application.

IIS Express
Its default internal web server in Visual Studio is typically used to build and run your application during development for you to test and debug codes. It is a lightweight, self-contained version of IIS optimized for developers. IIS Express makes it easy to use the most current version of IIS to develop and test websites. It has all the core capabilities of IIS 7 and above.

IIS Web Server

It comes built-into Windows. It provides server environment that is closest to what the live site will run under, and it is practical for you to install and work with IIS on your development machine. This article will walk you through how to publish and host your ASP.NET MVC application in your local IIS Web Server and debug hosted application in Visual Studio.

Install IIS Web Server
As IIS Web Server built-into Windows OS so it’s easy to install in few steps which are as follows in Windows 8.1:

Open the ‘Control Panel’ and click on Programs Setting.

There is another new ‘Program’ window opens and click on ‘Turn Windows feature on or off’ under Programs and Features section.

Now ‘Windows Features’ window opens and expands ‘Internet Information Services’ node.

After that expands child ‘World Wide Web Services’ node and check/enable all components under ‘Application Development Features’.

After that click ‘OK’ button to let Windows install the required files. Once installed you may now close the dialog. Now open an internet browser and type-in “localhost” to verify that IIS was indeed installed. It should bring up the following page below:

Star Rating in MVC Application
We create an ASP.NET MVC application which we used to set up on IIS web server. We develop star rating using css in this example so we create an empty MVC project in Visual Studio. We create a view model to pass data from view to controller and vice-versa as per following code snippet.
    namespace StarRating.Models  
    {  
        public class RatingViewModel   
        {  
            public int Rating   
          {  
                get;  
                set;  
            }  
        }  
    }  

We create a Rating controller which has GET and POST action method as per following code snippet.
    using StarRating.Models;  
    using System.Web.Mvc;  
      
    namespace StarRating.Controllers   
    {  
        public class RatingController: Controller   
        {  
            [HttpGet]  
            public ActionResult Index()   
            {  
                RatingViewModel model = new RatingViewModel();  
                return View(model);  
            }  
      
            [HttpPost]  
            public ActionResult Index(RatingViewModel model)   
            {  
                // Validation & Database opertions goes here  
                return View(model);  
            }  
        }  
    }  


We write css for rating star design on UI as following code snippet.
    .rating  
    {  
        unicode - bidi: bidi - override;  
        direction: rtl;  
        font - size: 30 px;  
    }  
      
    .rating span.star, .rating span.star   
    {  
        font - family: FontAwesome;  
        font - weight: normal;  
        font - style: normal;  
        display: inline - block;  
    }  
      
    .rating span.star: hover, .rating span.star: hover  
    {  
        cursor: pointer;  
    }  
      
    .rating span.star: before, .rating span.star: before  
    {  
        content: "★";  
        padding - right: 5 px;  
        color: #BEC3C7;  
    }  
      
    .rating span.star: hover: before, .rating span.star: hover: before, .rating span.star: hover~span.star: before, .rating span.star: hover~span.star: before   
    {  
        content: "★";  
        color: #41CAC0;  
    }  
      
    .rating span.star.active::before, .rating span.star.active::before, .rating span.star.active ~ span.star::before, .rating span.star.active ~ span.star::before  
    {  
    color: # 41 cac0;  
        content: "★";  
    }  

Now write the view on which rating star shows as per following code snippet.
    @model StarRating.Models.RatingViewModel  
    <div class="row">  
    <div class="col-lg-6">  
    @using (Html.BeginForm("Index", "Rating", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))  
    {  
    <h4>Star Rating</h4>  
    <hr />  
    <div class="form-group">  
    <label class="col-lg-2 col-sm-2 control-label" for="Rating">Rating</label>  
    <div class="col-lg-8">  
    <span class="rating">  
    @for (int i = 1; i <= 5; i++)  
    {  
    var starClass = "star";  
    if (Model.Rating == 6 - i)  
    {  
    starClass += " active";  
    }  
    <span data-value="@(6 - i)" class="@starClass"></span>  
    }  
    </span>  
    </div>  
    @Html.HiddenFor(m => m.Rating)  
      
    </div>  
    <div class="form-group">  
    <div class="col-md-offset-2 col-md-10">  
    <input type="submit" class="btn btn-default" value="Submit" />  
    </div>  
    </div>  
    }  
    </div>  
    </div>  
    @section Scripts{  
    @Scripts.Render("~/Scripts/rating-index.js")  
    }  

We write a JavaScript function to assign selected star value to hidden field so that we get this value on POST action on controller. The following code snippet is for the same.
    (function($)  
     {  
        function RatingIndex()   
      {  
            var $this = this;  
      
            function initialize()  
        {  
                $(".star").click(function()  
                 {  
                    $(".star").removeClass('active');  
                    $(this).addClass('active');  
                    var starValue = $(this).data("value");  
                    $("#Rating").val(starValue);  
                })  
            }  
            $this.init = function()   
            {  
                initialize();  
            }  
        }  
        $(function() {  
            var self = new RatingIndex();  
            self.init();  
        })  
    }(jQuery))  


Now we open project properties by right clicking on project. The default web server is set IIS Express with URL in the Web tab of properties as shown in figure 2. It means when we run this application from the Visual Studio then it build and run at local IIS Express server.




After that we run the application from the visual studio 

Deploy Application on IIS Web Server

We publish and host the web application on our development machine IIS Web Server so that we can set up same live environment on local development machine. To deploy an application on IIS Web Server we divide process in two parts one is publish and another is host.

Publish ASP.NET MVC Application from Visual Studio

To publish ASP.NET MVC project from Visual Studio, we follow following steps one by one.
Build ASP.NET MVC project /solution in Release mode.
Right click on ASP.NET MVC project and click on “Publish” menu. 

Now  Publish Web pane opens, and choose profile tab from left tab. There is a “Select or import a public profile” in which you can either choose existing one or create new publish profile as shown in following image.


Now clicks on “Ok” and move on Connection tab in Publish Web. Now we choose File System in publish method and choose desired location in Target Location which we will be used to map IIS.

Now we choose configuration mode Release as shownin the  below figure and click on Next button. There are some options such as Delete all existing files prior to publish which means delete all existing files in target location, publish folder, and create new files.

Now we get publish preview which shows publish path and profile name. Now we click on publish button and all published files created at target location.

Host ASP.NET MVC Application on IIS Web Server
As we have published code so now we host this code on IIS step by step.
Search inetmgr in search box and click on IIS manager icon.
In the IIS manager, Right clicks on Sites under Connections pane as show in following image.

Now we have following where we fill up all the information which is required to host ASP.NET MVC application on IIS Web Server.

Site name : Name of site
Application pool : .NETv4.5 (version of .net framework on which application run)
Physical path: Path of the published ASP.NET MVC application code and map to directory which have Web.config file.

Application
Now we set up binding for hosted application so that it can run on the 4.5 .NET Framework. You need to right click on hosted Website and expand Manage Website and click on Advanced Setting. The following image shows options for same.

Advance Setting
Now we set application pool for the application as shown in the following image.

Application pool setting
An IIS application pool is a grouping of URLs that is routed to one or more worker processes. Because application pools define a set of Web applications that share one or more worker processes, they provide a convenient way to administer a set of Web sites and applications and their corresponding worker processes.

Now we run the application using URL http://localhost/rating and get output same as figure 3.

As you can see we have still localhost in web URL to access the application so we make some more changes in configuration so that we can access it same as live site. There are follows:

Right click on hosted web application

Click on the Edit Binding option in the pane and opens Site Binding popup.
Select the website from Site Binding pop up and clicks on Edit button.
Edit Site Binding popup opens and we assign a value ‘dev.rating.com’ to Host name field in it.

Assign Host name

Now open your system hosts file from C:\Windows\System32\drivers\etc and make an entry for site host name as below
127.0.0.1 dev.rating.com

Now we run the application using URL http://dev.rating.com/rating and get output same as figure 3.

Debug ASP.NET MVC Application
When we run application from the Visual Studio with IIS Express then debug process auto attach and hits breakpoint accordingly. Now we run hosted application from IIS Web Server using above mentioned URL. To debug the application we follows following steps:

Click Debug option in Visual Studio menu.

Select ‘Attach to Process’ option from drop down pane as shown in following figure 13.

Debug process option
We attach w3wp.exe process to debug application as shown in below figure. Make sure application build configuration set is Debug. Set your breakpoint in application and debug accordingly.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: JWT Auth in ASP.NET MVC: C#.NET Secure REST API

clock July 8, 2025 08:54 by author Peter

This practical tutorial will teach you how to use C# and JWT (JSON Web Token) authentication to create a RESTful Web API in ASP.NET MVC. This is a cutting-edge and safe way to manage user authentication and safeguard your endpoints.

By the end of this tutorial, you’ll be able to.

  • Generate JWT tokens on login
  • Authenticate API calls using tokens
  • Secure endpoints so only logged-in users can access them

Tools Required

  • Visual Studio 2019/2022
  • .NET Framework (4.7 or later)
  • NuGet Package: System.IdentityModel.Tokens.Jwt

Step 1. Create a New ASP.NET Web API Project

  • Open Visual Studio
  • File → New → Project
  • Select ASP.NET Web Application (.NET Framework)
  • Name it JwtStudentAPI
  • Choose the Web API template and click Create

Step 2. Install Required NuGet Package
Open the Package Manager Console and run.
Install-Package System.IdentityModel.Tokens.Jwt

Step 3. Create Student Model
File: Models/Student.cs.
using System;

namespace JwtStudentAPI.Models
{
    public class Student
    {
        public string StudentId { get; set; }
        public string Name { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string ZipCode { get; set; }
        public string Major { get; set; }
    }
}

Step 4. Create Login Model
File: Models/UserCredential.cs.
namespace JwtStudentAPI.Models
{
    public class UserCredential
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

This is a simple model for a login payload.

Step 5. Add Token Generation Logic
File: Controllers/AuthController.cs.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Web.Http;
using JwtStudentAPI.Models;
using Microsoft.IdentityModel.Tokens;

namespace JwtStudentAPI.Controllers
{
    public class AuthController : ApiController
    {
        [HttpPost]
        [Route("api/auth/login")]
        public IHttpActionResult Login(UserCredential login)
        {
            if (login.Username == "admin" && login.Password == "pass123")
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("MySuperSecretKey12345");

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Name, login.Username)
                    }),
                    Expires = DateTime.UtcNow.AddMinutes(30),
                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha256Signature)
                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return Ok(new { token = tokenString });
            }

            return Unauthorized();
        }
    }
}


Explanation

  • Validates the hardcoded user (for demo).
  • Generates a JWT using a secret key.
  • Returns the token to the client.

Step 6. Create a Token Validation Handler
File: Handlers/JwtValidationHandler.cs.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.IdentityModel.Tokens;

namespace JwtStudentAPI.Handlers
{
    public class JwtValidationHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!request.Headers.Contains("Authorization"))
                return await base.SendAsync(request, cancellationToken);

            var token = request.Headers.Authorization?.Parameter;
            if (token == null)
                return request.CreateResponse(HttpStatusCode.Unauthorized, "Missing token");

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes("MySuperSecretKey12345");

            try
            {
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var identity = new ClaimsIdentity(jwtToken.Claims, "jwt");
                Thread.CurrentPrincipal = new ClaimsPrincipal(identity);
            }
            catch
            {
                return request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid token");
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}

Step 7. Register the JWT Handler
In Global.asax.cs, add this in Application_Start().
GlobalConfiguration.Configuration.MessageHandlers.Add(
    new JwtStudentAPI.Handlers.JwtValidationHandler()
);


Step 8. Create a Protected Student Controller
File: Controllers/StudentController.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using JwtStudentAPI.Models;

namespace JwtStudentAPI.Controllers
{
    [Authorize]
    public class StudentController : ApiController
    {
        private static List<Student> students = new List<Student>
        {
            new Student
            {
                StudentId = "S201",
                Name = "Arun Kumar",
                DateOfBirth = new DateTime(2000, 5, 15),
                ZipCode = "600001",
                Major = "IT"
            },
            new Student
            {
                StudentId = "S202",
                Name = "Divya S",
                DateOfBirth = new DateTime(2001, 3, 20),
                ZipCode = "641002",
                Major = "ECE"
            }
        };

        [HttpGet]
        [Route("api/student/{id}")]
        public IHttpActionResult Get(string id)
        {
            var student = students.FirstOrDefault(s => s.StudentId.Equals(id, StringComparison.OrdinalIgnoreCase));
            if (student == null)
                return NotFound();

            return Ok(student);
        }
    }
}


Step 9. Test Your API
1. Get Token
    POST to: http://localhost:[PORT]/api/auth/login
    Body

    {
      "Username": "admin",
      "Password": "pass123"
    }

Response
{
  "token": "eyJhbGciOi..."
}


2. Access Protected API
GET to: http://localhost:[PORT]/api/student/S202
Header: Authorization: Bearer [token]

Summary

  • You have now built a complete JWT-authenticated ASP.NET Web API. You’ve learned how to:
  • Generate a JWT token
  • Validate incoming tokens
  • Protect endpoints with [Authorize]

This is a scalable and secure authentication approach widely used in production systems.

Next Steps

  • Store credentials and keys in secure settings (config or environment variables)
  • Implement user registration and token refresh
  • Use HTTPS in all requests
  • Connect to a real database for dynamic user validation

Hands-On Ideas

  • Add role-based access (e.g., Admin vs Student)
  • Track token expiration
  • Add logout functionality
  • Test using Postman and Swagger

Happy coding with secure APIs! Please do comment your questions, which can help to learn better! Happy learning



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