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 Cheatsheet: An Easy-to-Use Manual

clock July 31, 2025 09:02 by author Peter

A framework called ASP.NET MVC is used to create web applications by following the Model-View-Controller pattern. It facilitates the separation of data, user interface, and application logic, making the code easier to scale, maintain, and test. With definitions, brief examples, and advice, this article serves as a straightforward reference for important ASP.NET MVC subjects. Both novices and those in need of a fast refresh will find it helpful.

1. Model-View-Controller (MVC) Pattern
Definition: MVC is a design pattern that separates an application into three parts:

  • Model: Handles data and business logic.
  • View: Displays the data to the user.
  • Controller: Handles user input and updates the Model or View.

Example
public class Student {
    public int Id { get; set; }
    public string Name { get; set; }
}


Important: This pattern improves the testability and maintainability of your code.

2. Routing

  • Definition: Routing maps URLs to controller actions.
  • Example

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

Important: Defined in RouteConfig.cs, used by Global.asax.

3. Controller
Definition: A controller handles incoming HTTP requests and returns a response.

Example
public class HomeController : Controller {
    public ActionResult Index() {
        return View();
    }
}


Important: Action methods return ActionResult.

4. ActionResult Types

Definition: ActionResult can return different types of responses.

Example
return View();            // Returns HTML view
return RedirectToAction("About");
return Json(data, JsonRequestBehavior.AllowGet);

Important: Choose based on the type of response needed.

5. Views
Definition: Views are UI templates written using Razor syntax.
Example (Index.cshtml)
<h2>Hello @Model.Name</h2>

Important: Views are strongly typed using @model directive.

6. Strongly Typed Views
Definition: Views that are linked to a specific model type.

Example
@model YourApp.Models.Student
<p>Name: @Model.Name</p>

Important: Helps avoid errors at runtime by providing IntelliSense.

7. HTML Helpers

Definition: Methods to create HTML elements in views.
Example
@Html.TextBoxFor(model => model.Name)

Important: Useful for creating forms and binding values to models.

8. Form Submission
Definition: Form data is posted to a controller using HttpPost.
Example
[HttpPost]
public ActionResult Create(Student student) {
    // Save to DB
    return RedirectToAction("Index");
}

Important: Use [HttpPost] to handle form submissions.

9. Model Binding
Definition: Automatically maps form values to model properties.
Example
public ActionResult Edit(Student student) {
    // 'student' is populated from form data
}


Important: Names of form fields must match model property names.

10. Model Validation
Definition: Data annotations are used to validate user input.
Example
[Required]
[StringLength(50)]
public string Name { get; set; }


Important: Validations are enforced on both the client and server sides.

11. TempData, ViewBag, ViewData
TempData: Used to pass data between actions (persists for one request).
ViewBag: A Dynamic object, used to pass data from the controller to the view.
ViewData: Dictionary object, similar to ViewBag.

Example
ViewBag.Message = "Hello";
return View();


Important: Prefer ViewModel for passing complex data.

12. Filters
Definition: Used for cross-cutting concerns like logging, authorization, etc.
Example
[Authorize]
public ActionResult Secret() {
    return View();
}

Important: Built-in filters include Authorize, HandleError, etc.

13. Partial Views
Definition: A part of a view reused in multiple pages.

Example
@Html.Partial("_StudentDetails", student)

Important: Good for reusable UI components.

14. Layout View

Definition: Acts like a master page for consistent layout.
Example (_Layout.cshtml)
    <body>
      <div>@RenderBody()</div>
    </body>


Important: Set the layout in views using @{ Layout = "_Layout.cshtml"; }.

15. Bundling and Minification
Definition: Combines and compresses CSS and JS files.
Example
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

Important: Improves load time by reducing request size.

16. Error Handling

Definition: Catch and handle errors gracefully.

Example
[HandleError]
public class HomeController : Controller {
    public ActionResult Error() {
        throw new Exception("Test");
    }
}


Important: Use custom error pages via web.config.

17. Scaffolding

  • Definition: Automatically generates a controller and views for a model.
  • Example: Right-click Model → Add → Controller → Use Scaffolding.
  • Important: Saves time during prototyping.

18. Entity Framework Integration
Definition: Used for database operations.
Example
    public class SchoolContext : DbContext {
        public DbSet<Student> Students { get; set; }
    }


Important: Supports Code First and Database First approaches.

19. Dependency Injection (DI)

Definition: Inject dependencies instead of creating them inside the class.
Example
    public HomeController(IStudentService service) {
        _service = service;
    }


Important: Use built-in or external DI containers like Unity or Autofac.

20. Security
Authentication: Use Identity for user login and registration.
Authorization: Use [Authorize] to restrict access.
Anti-Forgery
@Html.AntiForgeryToken()

Important: Always validate and sanitize inputs.\

21. Areas
    Definition: Areas are used to split a large application into smaller sections or modules.
    Example

    // In AreaRegistration
    public class AdminAreaRegistration : AreaRegistration {
        public override string AreaName => "Admin";

        public override void RegisterArea(AreaRegistrationContext context) {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }


Important: Helps organize projects with many controllers and views.

22. Custom Route Constraints
    Definition: Custom logic used to restrict which URLs match a route.
    Example
    routes.MapRoute(
        name: "YearRoute",
        url: "{controller}/{action}/{year}",
        constraints: new { year = @"\d{4}" }
    );

    Important: Use regular expressions or custom classes to define constraints.

23. Custom HTML Helpers
    Definition: Create your own helper methods for reusable HTML elements.
    Example
    public static class HtmlExtensions {
        public static MvcHtmlString HelloText(this HtmlHelper helper, string name) {
            return new MvcHtmlString($"<p>Hello {name}</p>");
        }
    }


    Important: Add namespace to web.config under <pages><namespaces>.

24. JsonResult
    Definition: Used to return JSON data from a controller.
    Example
    public JsonResult GetStudent() {
        var student = new { Id = 1, Name = "Riya" };
        return Json(student, JsonRequestBehavior.AllowGet);
    }

    Important: Useful for AJAX requests.

25. File Upload

    Definition: Upload files to server using a form.
    Example
    <form enctype="multipart/form-data" method="post">
        <input type="file" name="file" />
        <input type="submit" />
    </form>

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) {
    if (file != null) {
        var path = Path.Combine(Server.MapPath("~/Uploads"), file.FileName);
        file.SaveAs(path);
    }
    return View();
}

    Important: Set enctype="multipart/form-data" in the form.

26. Session Management
    Definition: Store user data between requests.
    Example
    Session["UserName"] = "Peter";
    var name = Session["UserName"];


   Important: Avoid overusing sessions due to memory concerns on the server.

27. Using ViewModels
    Definition: A class used to combine multiple models or additional data for the view.
    Example

    public class StudentViewModel {
        public Student Student { get; set; }
        public List<Subject> Subjects { get; set; }
    }

    Important: Keeps views clean and focused.

28. AJAX with jQuery
Definition: Load data or perform actions without refreshing the page.
Example
$.get("/Student/GetDetails", function(data) {
    $("#studentDiv").html(data);
});


Important: Controller action can return PartialView or JsonResult.

29. Web.config Settings
Definition: Configuration file for ASP.NET applications.
Example

<connectionStrings>
    <add name="DefaultConnection" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>

Important: Used for settings like connection strings, custom errors, etc.

30. Anti-Forgery Token
Definition: Prevents Cross-Site Request Forgery (CSRF) attacks.

Example
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
}


[ValidateAntiForgeryToken]
public ActionResult Save(Student student) {
// Save logic
}


Important: Always include in forms that modify data.

31. Authorization and Authentication
Definition: Control access to controllers and actions.

Example

[Authorize]
public ActionResult Dashboard() {
    return View();
}

Important: Use [AllowAnonymous] to allow public access if needed.

32. Custom Error Pages
Definition: Show user-friendly messages instead of raw errors.
Example in web.config

<customErrors mode="On">
    <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

Important: Always test error behavior after deployment.

33. Output Caching
Definition: Caches the result of controller actions to improve performance.

Example
[OutputCache(Duration = 60)]
public ActionResult News() {
    return View();
}

Important: Avoid caching dynamic or user-specific content.

34. Action Filters
Definition: Execute logic before or after action methods.
Example

public class LogActionFilter : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        // Log here
    }
}


Important: Can be used for logging, exception handling, etc.

Conclusion
ASP.NET MVC is a strong and flexible framework for building web applications. Knowing the key concepts like routing, controllers, views, model binding, and validation helps in creating clean and maintainable applications. This cheatsheet gives a quick look at the important topics, with examples and points to remember. It is a useful reference when you are coding or revising.



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



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Non-Action Selector In ASP.NET MVC

clock June 25, 2025 08:37 by author Peter

The Non-Action Selectors in ASP.NET MVC will be explained in this post. A public method in a controller that can be accessed via a URL is called an action method. Therefore, by default, a URL request can be used to invoke any public methods that are present in a controller. A Controller's Non-Action attribute can be used to limit access to public methods. Another built-in property that shows that a Controller's public method is not an action method is Non-Action. When we don't want that technique to be regarded as an action method, we employ it.

Let's see the Non-Action Selectors in action via this example.

Step 1
Open Visual Studio 2015 or an editor of your choice and create a new project.

Step 2
Choose "web application" project and give an appropriate name to your project.

Step 3
Select "empty" template, check on the MVC box, and click OK.

Step 4
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

Entity Framework gets added and the respective class gets generated under the Models folder.

Step 5
Right-click on Controllers folder add a controller.

Step 5
Right-click on Controllers folder add a controller.

A window will appear. Choose MVC5 Controller-Empty and click "Add".

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.

Controller without NonAction attribute
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using MvcActionSelectors_Demo.Models;  
       
    namespace MvcActionSelectors_Demo.Controllers  
    {  
        public class DepartmentController : Controller  
        {  
            private readonly EmployeeContext _dbContext=new EmployeeContext();  
       
            public ActionResult Index()  
            {  
                var department = _dbContext.Departments.ToList();  
                return View(department);  
            }  
       
            public string HelloWorld()  
            {  
                return "<h2>Hello World, Welcome to programming.</h2>";  
            }  
        }  
    }  


Controller with NonAction attribute

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using MvcActionSelectors_Demo.Models;  
       
    namespace MvcActionSelectors_Demo.Controllers  
    {  
        public class DepartmentController : Controller  
        {  
            private readonly EmployeeContext _dbContext=new EmployeeContext();  
       
            public ActionResult Index()  
            {  
                var department = _dbContext.Departments.ToList();  
                return View(department);  
            }  
       
            [NonAction]  
            public string HelloWorld()  
            {  
                return "<h2>Hello World, Welcome to programming.</h2>";  
            }  
        }  
    }  

Step 6
Right-click on Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page). Click on "Add".

Code for Index View
    @model IEnumerable<MvcActionSelectors_Demo.Models.Department>  
    @{  
        ViewBag.Title = "Index";  
    }  
       
    <h2>List of Department</h2>  
    <table class="table table-bordered">  
        <thead>  
        <tr>  
            <th>@Html.DisplayNameFor(m=>m.ID)</th>  
            <th>@Html.DisplayNameFor(m=>m.DepartmentName)</th>  
        </tr>  
        </thead>  
        <tbody>  
        @foreach (var dep in Model)  
        {  
            <tr>  
                <td>@dep.ID</td>  
                <td>@dep.DepartmentName</td>  
            </tr>  
        }  
        </tbody>  
    </table>  


Step 7
Build and run the project using Ctrl+F5.
http://localhost:56100/Department/HelloWorld

Now, if you navigate to http://localhost:56100/Department/HelloWorld, you will get an error the resource cannot be found as shown below.

In general, it’s a bad practice to have a public method in a Controller that is not an action method. If we have any such method for performing business calculations, it should be somewhere in the Model and not in the Controller. However, if for some reason, we want to have public methods in a controller and we don’t want to treat them as actions, then use Non-Action attribute. 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Razor and ASPX View Engine Distinctions in MVC

clock June 16, 2025 09:11 by author Peter

View Engine renders the view into HTML form to the browser. If we talk about a MVC application in the .Net Framework, it supports the following 2 view engines:

  • Razor View Engine
  • Web Form/Aspx View Engine

Differences
Entry with ASP.NET MVC          
Razor View Engine is an advanced view engine and introduced with MVC3. This is not a language but it is a markup syntax.
ASPX View Engine is the default view engine for the ASP.NET MVC that is included with ASP.NET MVC from the beginning.

Namespace

  • Razor View Engine supports System.Web.Razor.
  • ASPX View Engine supports System.Web.Mvc.WebFormViewEngine.

Layout /MasterPage               

  • In Razor View Engine we use Layouts.
  • In ASPX View Engine we use masterPages.

PartialPage /WebUserControl
  • In Razor View Engine we use PartialPage.
  • In ASPX View Engine we use WebUserControls.

Extension
  • Razor View Engine has .cshtml (with C#) and .vbhtml (with VB) extension for views, Layout and Partial views.
  • ASPX View Engine has a similar extension as in a simple web application like .aspx for the views, .acsx for UserControls and .master for Master Pages.

Performance
  • Razor Engine is a little slow compared to Aspx Engine.
  • Aspx Engine is faster compared to Razor Engine.
Syntax
  • ‘@’ symbol uses in Razor Engine to write the code. @Html.ActionLink("Login", "LoginView")
  • ‘<%:’ delimiters use as starting point and ‘ %>’ use as ending point. You can write the code between them in ASPX Engine.
  • <%: Html.ActionLink("Login ", " LoginView ") %> 

Cross-Site Scripting Attacks
  • Razor Engine prevents Cross-Site Scripting Attacks, in other words it encodes the script or HTML tags like <,> before rendering to view.
  • ASPX Engine does not prevent Cross-Site Scripting Attacks, in other words any script saved in the database will be fired while rendering the page.


ASP.NET MVC Hosting - HostForLIFEASP.NET :: Different Types Of Action Results In ASP.NET MVC

clock June 3, 2025 10:27 by author Peter

There are various kinds of Action Results in ASP.NET MVC. The output format varies depending on the action result. 

To obtain the desired result, a programmer employs several action outcomes. Action Results gives back the page view result for the specified request.


Action Result
Action Result is a result of action methods or return types of action methods. Action result is an abstract class. It is a base class for all types of action results.


The diagram shown below describes the abstract class of Action Result. There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().


Types of Action Results
There are different types of action results in ASP.NET MVC. Each result has a different type of result format to view the page.

  • View Result
  • Partial View Result
  • Redirect Result
  • Redirect To Action Result
  • Redirect To Route Result
  • JSON Result
  • File Result
  • Content Result

View Result
The view result is a basic view result. It returns basic results to view the page. View results can return data to the view page through which the class is defined in the model. The view page is a simple HTML page. Here, the view page has a “.cshtm” extension.
public ViewResult About()
{
    ViewBag.Message = "Your application description page.";
    return View();
}


View Result is a class and is derived from the “ViewResultBase” class. “ViewResultBase” is derived from Action Result. The view Result base class is an Action Result. Action Result is a base class of different action results.

View Result class is inherited from the Action Result class by the View Result Base class. The diagram shown above describes the inheritance of Action Results.

Partial View Result

Partial View Result returns the result to the Partial View page. A partial view is one of the views that we can call inside the Normal view page.
public PartialViewResult Index()
{
    return PartialView("_PartialView");
}

We should create a Partial view inside the shared folder, otherwise, we cannot access the Partial view. The diagram is shown above the Partial view page and Layout page because the layout page is a Partial view. Partial View Result class is also derived from the Action Result.

Redirect Result
Redirect result is returning the result to a specific URL. It is rendered to the page by URL. If it gives the wrong URL, it will show 404 page errors.
public RedirectResult Index()
{
    return Redirect("Home/Contact");
}


Redirect to Action Result
Redirect to Action result is returning the result to a specified controller and action method. The controller name is optional in the Redirect to Action method. If not mentioned, the Controller name redirects to a mentioned action method in the current Controller. Suppose the action name is not available but mentioned in the current controller, then it will show a 404-page error.
public ActionResult Index()
{
    return RedirectToAction("Login", "Account");
}

JSON Result
JSON result is a significant Action Result in MVC. It will return a simple text file format and key-value pairs. If we call the action method, using Ajax, it should return a JSON result.
public ActionResult Index()
{
    var persons = new List<Person1>
    {
        new Person1 { Id = 1, FirstName = "Harry", LastName = "Potter" },
        new Person1 { Id = 2, FirstName = "James", LastName = "
Peter" }
    };

    return Json(persons, JsonRequestBehavior.AllowGet);
}

While returning more data in JSON format, there is a need to mention the maximum length. Assign the maximum length of data Using the “MaxJsonLength” property.
public ActionResult Index()
{
    var persons = new List<Person1>
    {
        new Person1 { Id = 1, FirstName = "Harry", LastName = "Potter" },
        new Person1 { Id = 2, FirstName = "James", LastName = "Peter" }
    };

    var jsonResult = Json(persons, JsonRequestBehavior.AllowGet);
    jsonResult.MaxJsonLength = int.MaxValue;
    return jsonResult;
}


File Result
File Result returns a different file format view page when we implement the file download concept in MVC using file result. Simple examples of file results are shown below.
public ActionResult Index()
{
    return File("Web.Config", "text");
}


Output 

Content Result
Content result returns different content formats to view. MVC returns different formats using content returns like HTML format, Java Script format and any other format.

Example
public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";

    return View();
}

public ActionResult Index()
{
    return Content("<script>alert('Welcome To All');</script>");
}

Output

Conclusion

This article explains about Action Results. It is very useful for new MVC learners and students.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Enhanced CRUD functionality for GridView in ASP.NET Core MVC with Redshift (using C# 14 Features)

clock May 9, 2025 09:51 by author Peter

It takes a thorough understanding of both backend data infrastructure and the newest features of C# 14 to enable CRUD operations in a GridView for report purposes when utilizing Amazon Redshift as the database of an ASP.NET MVC Core application. This article discusses in depth how this integration could be carried out in a robust, scalable manner with maximized performance and maintainability.

Setting Up the Environment
Prior to diving in with code, ensure your development environment contains.
ASP.NET Core MVC framework (most recent stable version)
C# 14 support is enabled in your project
AWS SDK for .NET and Redshift Data API Client
Entity Framework Core (EF Core) or Dapper for ORM (depending on your choice)


Connecting to Redshift
Redshift natively does not support direct connections using the usual EF Core due to its PostgreSQL heritage and some limitations. The secure, serverless way of accessing the Redshift Data API is what is recommended. The following NuGet package must be installed.
Install-Package AWSSDK.RedshiftDataAPIService

Establish a connection using your AWS credentials and set up the RedshiftDataClient.
var client = new AmazonRedshiftDataAPIServiceClient(
    "your-access-key",
    "your-secret-key",
    RegionEndpoint.USEast1
);

CRUD Operations Implementation
Create
Let's insert records by invoking SQL commands through the Data API.
var sqlStatement = "INSERT INTO reports (title, content, created_at) VALUES (:title, :content, :created_at)";

var parameters = new List<SqlParameter>
{
    new SqlParameter("title", report.Title),
    new SqlParameter("content", report.Content),
    new SqlParameter("created_at", DateTime.UtcNow)
};
await client.ExecuteStatementAsync(new ExecuteStatementRequest
{
    Sql = sqlStatement,
    Parameters = parameters,
    ClusterIdentifier = "your-cluster-id",
    Database = "your-database",
    DbUser = "your-db-user"
});


Read
Let's fetch data for displaying in the GridView.
var response = await client.ExecuteStatementAsync(new ExecuteStatementRequest
{
    Sql = "SELECT * FROM reports ORDER BY created_at DESC",
    ClusterIdentifier = "your-cluster-id",
    Database = "your-database",
    DbUser = "your-db-user"
});

// Map the response to your model


Update
Let's update existing records.
var sqlStatement = "UPDATE reports SET title = :title, content = :content WHERE id = :id";
var parameters = new List<SqlParameter>
{
    new SqlParameter("id", report.Id),
    new SqlParameter("title", report.Title),
    new SqlParameter("content", report.Content)
};
await client.ExecuteStatementAsync(new ExecuteStatementRequest
{
    Sql = sqlStatement,
    Parameters = parameters,
    ClusterIdentifier = "your-cluster-id",
    Database = "your-database",
    DbUser = "your-db-user"
});


Delete
Let's remove records as follows.
var sqlStatement = "DELETE FROM reports WHERE id = :id";

var parameters = new List<SqlParameter>
{
    new SqlParameter("id", report.Id)
};
await client.ExecuteStatementAsync(new ExecuteStatementRequest
{
    Sql = sqlStatement,
    Parameters = parameters,
    ClusterIdentifier = "your-cluster-id",
    Database = "your-database",
    DbUser = "your-db-user"
});

Enrichments with C# 14 Features
C# 14 also features collection expressions and pattern matching enhancements that can make data mapping and data manipulation easier. For instance, parameter initialization list using collection expressions and result set processing using pattern matching can make your CRUD operations easier.

Security and Best Practices

  • Call APIs securely using IAM Roles and Policies.
  • Parameterize all SQLs to prevent SQL injection.
  • Use aggressive error handling to catch exceptions nicely within a classically beautiful style.
  • Max out Redshift's performance with sorts and named styles of distributions up to their capacities for doing them.

This trend is supported by a clean, green method of presenting report data in an ASP.NET Core MVC-based GridView with Amazon Redshift and C# 14-driven. Additional features can include asynchronous data loading with SignalR, dynamic filtering, and scheduling of reports.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Transaction In MVC Using Entity Framework

clock April 30, 2025 08:09 by author Peter

This article describes how to utilize transactions in ASP. Net MVC to save records in various database tables by utilizing the entity framework code first method.

What’s the agenda?
Here I will show a simple form, where I will be storing the user's basic information in one table and multiple educational details in another table where the educational table will store the user table reference id.
 
Here I have used

  • ASP.NET MVC 4
  • MSSQL 2012 as Database.
  • Entity Framework code first approach.
  • From nuget I added reference to Entity Framework.

Step 1: Open Visual Studio 2013, click New Project.
Under Installed, Templates, Visual C#, click Web and provide the name and click OK.

Step 2
After this a window will pop up from Template, select Empty and then select MVC.
 
Step 3
After this point from Solution Explorer,  click on Solution, Add, then New Project.
 
Step 4
After this a window will pop up, click Installed, Visual C#, then Class Library and click OK.
 
Step 5
Now Rename the Class1 name to User under DbEntity and write the following code:
    using System;  
    using System.Collections.Generic;  
    using System.ComponentModel.DataAnnotations;  
    using System.ComponentModel.DataAnnotations.Schema;  
      
    namespace DbEntity  
    {  
        [Table("tblUser")]  
        public class User  
        {  
            [Key]  
            public int RefUserID { get; set; }  
            public string EmplCode { get; set; }  
            public string EmplName { get; set; }  
            public string CreatedBy { get; set; }  
            public DateTime? CreatedDate { get; set; }  
            public bool IsDeleted { get; set; }  
            public string DeletedBy { get; set; }  
            public DateTime? DeletedDate { get; set; }  
      
            public List<UserEducation> objUsrEducation { get; set; }  
        }  
    }  

Step 6
Now add another class and name it UserEducation User under DbEntity and write the following code:
    using System;  
    using System.ComponentModel.DataAnnotations;  
    using System.ComponentModel.DataAnnotations.Schema;  
      
    namespace DbEntity  
    {  
        [Table("tblUsrEducationDetail")]  
        public class UserEducation  
        {  
            [Key]  
            public int ID { get; set; }  
            public int RefUserID { get; set; }  
            public string InstitutionName { get; set; }  
            public string InstitutionType { get; set; }  
            public string CreatedBy { get; set; }  
            public DateTime? CreatedDate { get; set; }  
            public bool IsDeleted { get; set; }  
            public string DeletedBy { get; set; }  
            public DateTime? DeletedDate { get; set; }  
        }  
    }  


Step 7
Create a dbContext class as follows. Before creating this class install Entity Framework from NuGet Packages.
    using System.Data.Entity;  
      
    namespace DbEntity.Constent  
    {  
        public class MultiFileDbContext : DbContext  
        {  
            public DbSet<User> ObjUserData { get; set; }  
            public DbSet<UserEducation> objUserEducation { get; set; }  
        }  
    }  


Step 8
Changing Web.Config File,
    <connectionStrings>  
        <add name="MultiFileDbContext" connectionString="Data Source=PDM-SABYASA-LA\SQLEXPRESS;Initial Catalog=DemoMultiFileUserDb;User ID=sa;Password=Admin@1234;" providerName="System.Data.SqlClient" />  
      </connectionStrings>  


After this the database with name DemoMultiFileUserDb and tables tblUser and tblUsrEducationDetail with columns as per class parameters will be created after doing an Insert/Update/Delete operation.
 
Step 9
I have created a Controller for storing user details as per the following codes,
    public ActionResult Index()  
           {  
               return View();  
           }  
           [ValidateAntiForgeryToken]  
           [HttpPost]  
           public ActionResult Index(User ObjUserData)  
           {  
               using (var context = new MultiFileDbContext())  
               {  
                   using (DbContextTransaction dbTran = context.Database.BeginTransaction())  
                   {  
                       try  
                       {  
                           User pd = new User()  
                           {  
                               EmplCode = ObjUserData.EmplCode,  
                               EmplName = ObjUserData.EmplName  
                           };  
                           context.ObjUserData.Add(pd);  
                           context.SaveChanges();  
      
                           var id = pd.RefUserID;  
      
                           var usrFile = ObjUserData.objUsrEducation;  
                           if (usrFile != null)  
                           {  
                               foreach (var item in usrFile)  
                               {  
                                   item.RefUserID = id;  
                                   context.objUserEducation.Add(item);  
                               }  
                           }  
                           context.SaveChanges();  
                           dbTran.Commit();  
                       }  
                       catch (DbEntityValidationException ex)  
                       {  
                           dbTran.Rollback();  
                           throw;  
                       }  
                   }  
               }  
               return View();  
           }  

Step 10
I have created view as per the controller action,
    @{  
        ViewBag.Title = "Index";  
    }  
    <style>  
        body {  
            font-family: arial;  
            font-size: 12px;  
            margin: 20px;  
        }  
      
        table {  
            border-top: 2px solid #708cb7;  
        }  
      
            table td {  
                font-size: 12px;  
                padding: 5px 20px;  
                border: 1px solid #e1eaf9;  
            }  
    </style>  
      
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
    {  
        @Html.AntiForgeryToken()  
        <table>  
            <tr>  
                <td>Emp Code:  </td>  
                <td><input id="txtEmpCode" type="text" name="EmplCode" placeholder="Employee Code"></td>  
            </tr>  
            <tr>  
                <td>Emp Name:</td>  
                <td><input id="txtEmpName" type="text" name="EmplName" placeholder="Employee Name"></td>  
            </tr>  
        </table>  
        <br />  
        <table>  
            <tbody id="_qualification">  
            </tbody>  
            <tfoot>  
                <tr>  
                    <td colspan="7">  
                        <input id="btnAddCertificate" type="button" value="+">  
                    </td>  
                </tr>  
            </tfoot>  
    </table>  
        <br/>  
        <button type="submit">SUBMIT</button>  
    }  
      
    <script type="text/javascript">  
      
        $(document).on('click', '#btnAddCertificate', function () {  
            $.get("../content/Repeater/rptData.html", function (data) {  
                $('#_qualification').append(data);  
            });  
      
            var _time = 1000;  
      
            setTimeout(function () {  
                var i = 0;  
                $('._repeatExp').each(function () {  
                    $(this).find('.txtInstName').attr('name', "objUsrEducation[" + (i) + "].InstitutionName");  
                    $(this).find('.ddlEducationType').attr('name', "objUsrEducation[" + (i) + "].InstitutionType");  
                    i++;  
                });  
            }, _time);  
        });  
      
    </script>  


Step 11
I have also added some js and css along with J query to add and remove more records. You can find all in the attached project files. The view will look like this.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Using Serilog to Implement Logging in ASP.NET Core MVC

clock April 16, 2025 08:40 by author Peter

Logging serves as a crucial component of application development, functioning as a black box that records events, providing insight into what occurred when it took place and the reasons behind various actions. In this blog, I will guide you through the process of integrating Serilog, a robust structured logging library, into an ASP.NET Core MVC application. We will explore the necessary steps, starting from the installation of Serilog to its configuration for logging into both files and the console. Additionally, practical examples from a real-world project will be included to illustrate these concepts. Whether you are new to logging or seeking to enhance your diagnostic capabilities, this guide offers a comprehensive approach to achieving professional-grade logging.

What is Serilog?
Serilog is a clean, easy-to-setup logging library for .NET. It supports:

  • Structured logging
  • Multiple sinks (e.g., Console, File, Seq, etc.)
  • Enrichment for contextual logs
  • Rolling log files
  • Helpful for Debugging

Step 1. Install Serilog Packages
Open the Package Manager Console in Visual Studio and run:
Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.File
Install-Package Serilog.Sinks.Console


Step 2. Configure Serilog in Program.cs

Open your Program.cs file and configure Serilog like this:
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .WriteTo.Console()
    .WriteTo.File("Logs/log.txt", rollingInterval: RollingInterval.Day)
    .Enrich.FromLogContext()
    .CreateLogger();

builder.Host.UseSerilog();

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Log application startup
Log.Information("Application is starting...");

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

try
{
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly.");
}
finally
{
    Log.CloseAndFlush();
}

Step 3. Use Serilog in Your Controllers
You can inject ILogger<T> into your controllers like this:
public class TaskController : Controller
{
    private readonly ILogger<TaskController> _logger;

    public TaskController(ILogger<TaskController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Fetching all tasks...");
        return View();
    }

    public IActionResult Create()
    {
        _logger.LogInformation("Rendering Create Task view.");
        return View();
    }

    [HttpPost]
    public IActionResult Create(TaskModel model)
    {
        if (ModelState.IsValid)
        {
            _logger.LogInformation("Task created: {@Task}", model);
            // Save to DB (not shown)
            return RedirectToAction("Index");
        }

        _logger.LogWarning("Invalid task model submitted.");
        return View(model);
    }
}

// Use structured logging with {@Object} to log the full object for better diagnostics.


Clean Up
Always remember to flush logs using:
Log.CloseAndFlush();

This ensures all logs are written before your app shuts down.

Sample Log Output

Here's what your log.txt might look like:
[Information] Fetching all tasks...

[Information] Task created: { Title: "Write Blog", DueDate: "2025-04-15", IsCompleted: false }

[Warning] Invalid task model submitted.


Conclusion
The method of integrating Serilog into an ASP.NET Core MVC application is simple and efficient. Developers can have complete control over the logging process and specify exactly how and where logs are recorded by putting a few lines of configuration into place. This approach is useful not just during the development stage but also in production settings, where it is essential for efficient application monitoring and troubleshooting. This method works well for monitoring and debugging in production as well as during development.



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