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 :: 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.



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.



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