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 :: 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 :: Working With Built-In HTML Helper Classes In ASP.NET MVC

clock March 18, 2025 09:19 by author Peter

We may programmatically generate HTML Controls by using the HTML Helper class. View renders HTML text using HTML Helpers. The method HTML Helpers (Mostly) yields a string. Using HTML Helper classes is not required when creating an ASP.NET MVC application. Although we don't need them to create an ASP.NET MVC application, HTML Helpers facilitate the quick building of a view. Because HTML Helpers don't use ViewState or have an event model, they are lighter than ASP.NET Web Form controls.

HTML Helpers are categorized into three types:

  • Inline HTML Helpers
  • Built-in HTML Helpers
  • Custom HTML Helpers

In this Article, we will cover Built-In HTML Helpers. We will see Inline and Custom HTML Helpers in the upcoming article of this series.
Built-in HTML Helpers are further divided into three categories:

  • Standard HTML Helpers
  • Strongly Typed HTML Helpers
  • Templated HTML Helpers

Standard HTML Helpers
Standard HTML Helpers use to render the most common type of HTML controls like TextBox, DropDown, Radio buttons, Checkbox etc. Extension methods of HTML Helper classes have several overloaded versions. We can use any one according to our requirement. Let’s see some of the Standard HTML Helpers:

Form: For creating Form element, we can use BeginForm() and EndForm() extension method.

BeginForm helper implements the IDisposable interface, which enables us to use using keyword.

Label: Label method of HTML helper can use for generating label element. Label extension method have 6 overloaded versions.

TextBox
TextBox Helper method renders a textbox in View that has specified name. We can also add attributes like class, placeholder etc. with the help of overloaded method in which we have to pass objects of HTML Attributes.

 
We can also set the value In Textbox by passing a value in TextBox extension method.

TextArea: TextArea Method renders <textarea> element on view.


RadioButton
RadioButton can be rendered in the view using the RadioButton Helper method. In the simplest form, RadioButton Helper method takes three parameters i.e. name of the control, value and Boolean value for selecting the value initially.

 
CheckBox: CheckBox helper method renders a checkbox and has the name and id that you specify.



In the above example, Did you noticed an Additional input element? In case if you unchecked the checkbox or checkbox value not selected then you will get the value from the hidden field.

DropDownlist: DropDownList helper renders a drop down list.  
Password: Password Helper method renders input type as password.

Hidden: Hidden Helper method renders a Hidden field.

 
Strongly Typed Helper method:
Just like Standard Helper, we have several strongly typed methods.
Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.CheckboxFor(), Html.RadioButtonFor(), Html.ListBoxFor(), Html.PasswordFor(), Html.HiddenFor(), Html.LabelFor() etc.
 
Strongly Typed Helper requires lambda expressions. For using Strongly Typed Helper method, Firstly We have to make Strongly Typed View.

Let’s create a simple example:
Create an empty MVC Application and Add a Student class in model.

    public class Student  
        {  
            public int RollNo { get; set; }  
            public string Name { get; set; }  
      
            public string Gender { get; set; }  
            public string City { get; set; }  
      
            [DataType(DataType.MultilineText)]  
            public string Address { get; set; }  
                  
        }  


In Student class, I have added DataType attribute on Address property. I have added this attribute for showing a Templated HTML Helper example along with strongly Typed Helper method example. DataTypeAttribute class is present in System.ComponentModel.DataAnnotations namespace.

Now Add an empty controller and Name it as HomeController.

    [HttpGet]  
    public ActionResult Index()  
    {  
           return View();  
    }  
      
    [HttpPost]  
    public ActionResult Index(Student stud)  
    {  
            return View();  
    }  

Right click on Index Action method for get request and click on Add View. Select Student Model class and Select empty template. Click on Add.

Go to view and Add the following code. I am not going to use any scaffolding template for this example.
    @model StronglyTypedHTMLHelper.Models.Student  
      
    @{  
        Layout = null;  
    }  
      
    <!DOCTYPE html>  
      
    <html>  
    <head>  
        <meta name="viewport" content="width=device-width" />  
        <title>Index</title>  
    </head>  
    <body>  
        <div>  
            @using(@Html.BeginForm("Index","Home",FormMethod.Post)){  
            <table>  
                <tr><td>@Html.LabelFor(m=>Model.RollNo)</td><td>@Html.TextBoxFor(m=>Model.RollNo)</td></tr>  
                <tr><td>@Html.LabelFor(m => Model.Name)</td><td>@Html.TextBoxFor(m => Model.Name)</td></tr>  
                <tr><td>@Html.LabelFor(m => Model.Gender)</td><td>Male:@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked="checked"})Female:@Html.RadioButtonFor(m => m.Gender, "Female", true)</td></tr>  
                <tr><td>@Html.LabelFor(m => Model.City)</td><td>@Html.TextBoxFor(m => Model.City)</td></tr>  
                <tr><td>@Html.LabelFor(m => Model.Address)</td><td>@Html.EditorFor(m => Model.Address)</td></tr>  
                <tr><td></td><td><input type="submit" value="Submit"/></td></tr>  
            </table>  
            }   
        </div>  
    </body>  
    </html>  


In above code, we have bounded helpers with the model property using lambda expression. EditorFor is Tempate HTML Helper which will generate HTML element based upon the datatype of Address property of Student class.
 
Preview:

Fill the form and click on submit. Request comes to Index Action method with [HTTPPost] attribute, from here we can get all posted values from the form and we can use that student object for any kind of Data Operations.

Template Helper Method
These methods are very flexible and generate the HTML element based on the properties of the model class. We have already seen an EditorFor Helper method in the previous example, which generates TextArea element because we have declared MultiLine Datatype on Address property. Display, DisplayFor,Editor and EditorFor are the examples of Template Helper method.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Effectively Download Big Files in ASP.NET MVC

clock February 3, 2025 05:57 by author Peter

In order to download large files in ASP.NET MVC efficiently, you must maximize memory use, avoid timeouts, and guarantee a seamless user experience. The best methods are listed below:

1. Make use of FileStreamResult, which is effective for big files.
By doing this, the file is streamed rather than fully loaded into memory.

public ActionResult DownloadLargeFile()
{
string filePath = Server.MapPath("~/Files/LargeFile.zip"); // Adjust file path
string fileName = "LargeFile.zip";

if (!System.IO.File.Exists(filePath))
{
    return HttpNotFound("File not found.");
}

var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(stream, "application/octet-stream", fileName);
}

Why?
Streams the file without consuming memory.
Works well for large files (e.g., >1GB).

2. Use Response.Write to Stream File in Chunks
This method writes file in chunks to prevent excessive memory usage.
public void StreamLargeFile()
{
string filePath = Server.MapPath("~/Files/LargeFile.zip");

if (!System.IO.File.Exists(filePath))
{
    Response.StatusCode = 404;
    Response.End();
    return;
}

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=LargeFile.zip");

const int bufferSize = 1024 * 1024; // 1MB chunks
byte[] buffer = new byte[bufferSize];

using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
    int bytesRead;
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        Response.OutputStream.Write(buffer, 0, bytesRead);
        Response.Flush(); // Sends the chunk immediately to the client
    }
}

Response.End();
}


Why?
Sends 1MB chunks, preventing high memory usage.
Flushes data after each chunk to avoid server timeouts.

3. Asynchronous Streaming (Recommended for Web API)
For MVC + Web API applications, use an async stream for optimal performance.
public async Task<IActionResult> DownloadLargeFileAsync()
{
string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Files", "LargeFile.zip");

if (!System.IO.File.Exists(filePath))
{
    return NotFound("File not found.");
}

var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true);
return File(stream, "application/octet-stream", "LargeFile.zip");
}

Why?
Asynchronous file streaming prevents thread blocking.
useAsync: true optimizes I/O operations.

4. Enable Large File Downloads in Web.config
Modify web.config to allow large downloads:
<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483648" /> <!-- 2GB -->
    </requestFiltering>
</security>
</system.webServer>

Why?
Increases max file size limit (default is 30MB in IIS).

5. Use Content-Disposition Header (For Better Browser Support)
If the filename contains special characters, encode it properly:
public ActionResult DownloadLargeFile()
{
string filePath = Server.MapPath("~/Files/LargeFile.zip");
string fileName = "Large File.zip";

var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var cd = new System.Net.Mime.ContentDisposition
{
    FileName = fileName,
    Inline = false // Forces download
};
Response.Headers.Add("Content-Disposition", cd.ToString());

return File(stream, "application/octet-stream");
}


Why?
Prevents filename issues (especially in Chrome & Edge).

6. Optimize IIS for Large Files
If you use IIS, increase timeout settings:

appcmd set config /section:serverRuntime /uploadReadAheadSize:10485760
appcmd set config /section:system.webServer/serverRuntime /maxRequestEntityAllowed:2147483648

Why?
Prevents timeouts for large file downloads.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Connection String in ASP.NET Core MVC .NET 8

clock December 16, 2024 06:41 by author Peter

You will discover how to use and manage connection strings in the program in this post.

The following queries will be addressed:

  • A Connection String: What Is It?
  • How many ways exist for connection strings to be defined and managed?
  • Examples of Codes

What is a Connection String?
The connection string is one kind of text string that is used to establish a connection from the application to the database server database. The connection string is the collective information of the data source, database name, user name, and password.

How many ways to define and manage connection strings?

Following ways to declare and manage the connection strings:

  • AppSettings.json
  • Environment Settings
  • Static Class

AppSettings.json
Using the AppSettings.json file, you can easily write a connection string.

Define Connection-String
Creating a separate object under the main json object just below Logging.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "MyConnectionString": "Server=xxx.xx.xxx.xx;Database=dbTest;User=xxxxxxx;Password=xx@xx;TrustServerCertificate=True"
  },
  "AllowedHosts": "*"
}


Using Connection-String
Open the HomeController.cs file and update the code.
public class HomeController : Controller
{
    // Inject the IConfiguration interface into your controller to access the connection string from appsettings.json file
    private readonly IConfiguration _configuration;
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        // Get the connection string
        string connectionString = _configuration.GetConnectionString("MyConnectionString");
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}


Environment Settings
Using the environment setting, it takes more steps to configure the connection string than the appsettings.json file.
Note. You can set environment variables in two ways.

Command Window
setx MyDbConnect "Server=(localdb)\\MSSQLLocalDB;Database=dbMyDb;Trusted_Connection=Tr

Edit Environment Variable Dialog box.

Search for “environment” in the start menu.
You can add the new environment variable by clicking the NEW button.

You can check and update the connection string in Local environment variables

To fetch the local environment variables
string Connt = Environment.GetEnvironmentVariable("MyDbConnect");

Note. You may get null value from above line, you have to restart the Visual Studio because visual studio read Environment Variable at startup only.

Static Class

Create a static class and static property to set the connection string.
public static class DbConnect
{
    public static string DbConnectionString { get; set; } =
        "Server=xxx.xx.xxx.xx;Database=dbTest;User=xxxxxxx;Password=xx@xx;TrustServerCertificate=True";
}

You can use it in the following way:
string ConStr = DbConnect.DbConnectionString;

Happy Coding.



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