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



ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.NET MVC C# Demo Registration Integration with External APIs

clock November 26, 2024 06:46 by author Peter

Integrating external services into contemporary web applications can greatly increase functionality and enhance user experience. One example of an integration is with car registration systems, where administrators can easily handle vehicle data thanks to APIs. The method of incorporating an automobile registration API into an ASP.NET MVC application will be examined in this article. In particular, we will concentrate on a technique that connects to an external service (base API) for tag registration in order to add a car to an administrator's system.


The technique under discussion manages a number of tasks, including data preparation, HTTP request sending, response processing, and error management. You will have a firm grasp on how to integrate external APIs into your own web applications by the end of this tutorial, guaranteeing seamless communication between your system and outside services.

Code
public async Task<ActionResult> Demoadminvehicle(GetDemoadmin model)
{
    // Create an instance of GetDemoadmin
    GetDemoadmin vehiInfo = new GetDemoadmin();

    // Set the properties of the model
    model.Id = Convert.ToInt32(Session["Id"]);
    model.MobileNumber = model.MobileNumber;
    model.name = model.name;
    model.no = model.no;

    // Base URL for the API
    string Baseurl = "https://api.base.id/v1/clint/demo";

    // Create request payload
    var requestData = new
    {
        consent = true,
        consentText = "I approve baseto capture",
        Number = model.no
    };

    // Serialize the object to JSON
    string jsonContent = JsonConvert.SerializeObject(requestData);

    // Create the HTTP web request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Baseurl);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Accept = "application/json";
    request.Headers.Add("Authorization", "bse w6rCvk51oXJiKZgbhJeaHROpRe7AJf3T%2fmdiwjszkaU%2fnNgA%2f2");

    // Write JSON content to the request stream
    using (StreamWriter writer = new StreamWriter(await request.GetRequestStreamAsync()))
    {
        await writer.WriteAsync(jsonContent);
    }

    try
    {
        // Get the response from the server
        using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseData = await reader.ReadToEndAsync();
                vehiInfo = JsonConvert.DeserializeObject<GetResponseclientdash>(responseData);
                model.tagId = vehiInfo.tagId;

                Console.WriteLine("Response received successfully: " + responseData);
            }
        }
    }
    catch (WebException ex)
    {
        clsErrorLog.ErrorLog(
            "Exception: " + ex.ToString(),
            "Demoadminvehicle",
            "Demoadminvehicle"
        );
    }

    // Call provider method and return result as JSON
    var res = DemoProvider.Demoadminvehicle(model);
    return Json(res, JsonRequestBehavior.AllowGet);
}

The Demoadminvehiclemethod is responsible for registering a vehicle under a specific admin by making a request to the baseAPI, which handles vehicle services. This is achieved by accepting user input in the form of a GetDemoadmin object, preparing the request, and handling both the request and response.

Step-by-Step Breakdown
1. Model Preparation
The method begins by initializing a new instance of the GetDemoadmin class (vehiInfo) and sets the necessary properties from the input model (model). The properties include customer information such as NO, name, and VehicleNo. Additionally, the Id is fetched from the session (which may represent the location or specific context related to the admin).

2. Setting Up API Request Data
The next step is to configure the data that will be sent to the external API. A requestData anonymous object is created to include essential information, like the vehicle registration number and consent text. The consent is marked as true, indicating that the user agrees to the terms and conditions for data processing.

This request data is serialized into a JSON string using JsonConvert.SerializeObject will be the body of the HTTP POST request.

3. Setting Up the HTTP Web Request

With the data ready, the method sets up an HTTP POST request using the HttpWebRequest class. The request headers are configured to accept JSON responses, and an Authorization header is added for security purposes (Basic authentication).

The baseurl is the endpoint for the BureauID API, which provides fastag-related services.

4. Sending the Request
The method uses a StreamWriter to send the serialized JSON content to the API. This is done asynchronously using await writer.WriteAsync(jsonContent);.

5. Handling the API Response
Once the request is sent, the code awaits the response from the server. If successful, the response data is read and deserialized into a GetDemoadmin object. This object contains a tagId property, which is important to associate the vehicle with a unique identifier.

6. Error Handling
In the event of an error, such as network issues or API downtime, the method catches a WebException and logs the error using a custom logging class (clsErrorLog). This ensures that the application doesn't crash and that relevant error details are stored for debugging.

Output

Conclusion
The Demoadminvehicle method is a crucial part of the vehicle registration process for an admin, interacting with an external API for vehicle fastag services. It demonstrates how to handle HTTP requests and responses asynchronously, ensure data privacy with user consent, manage errors gracefully, and return useful information back to the client.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: MVC Architecture & MVC Life Cycle

clock October 25, 2024 08:58 by author Peter

Model View Controller, or MVC for short, is a design pattern used to create applications rather than a programming language. Three components will make up the application that was created utilizing the MVC design pattern. Which model will house all of the data that can be retrieved at the user's request?

The Controller will have business logic code, and the View will have user interface code. We shall examine a graphical example of MVC to gain a better understanding of it.

The Properties of MVC is.

  • Loose Coupling
  • Lightweight code
  • Effective look
  • Testing is Very Easy
  • Rapid application integrated development.

MVC Architecture
The architecture of MVC can be seen in the following figure.

Explanation
User will make request for the page which user would like to retrieve. Requested page will go to controller and on controller Route.Config will be checked. Requested page will get transfer to Model from Controller.

On Model there will be 2 steps.

  • Page initialization will get started.
  • Then result set will be generated.

After these operation result set will get unload to View through view engine.

Responsibility of view engine

  • View Engine get the request from Controller
  • The requested page will get executed
  • The result got by the execution process will get deliver to View.

Life cycle of MVC
Life Cycle of MVC is in the following figure.

Explanation of MVC Life Cycle
Step 1. User will make request for page
Step 2. Route.Config will get check on Controller
Step 3. After Route.Config validation request will get transfer from Controller to Model
Step 4. Page request will go to Model & on Model the following operation will perform.

  • Page initialization will start after the initialization of the page.
  • One result set will get generated.

Step 5. Generated result set will be delivered to the Controller from the Model.
On Model Page validation operation will perform.

Step 6. After page validation on controller, Page will deliver to View through View engine.

Step 7. Now user can see requested page as response page.
Life Cycle of MVC can be seen as in the following figure.


Explanation

  • User will make page request.
  • Route.Config of requested page will get checked on Controller.
  • Page initialization will be performing on Model and after page initialization one result set will get generated.
  • Generated Result set will be getting delivered to the Controller from Model.
  • Result set will get validated (Page Validation) and after page validation Result set will get delivred to View through view engine.

Recap
MVC Stands for Model View Controller, which is a design pattern. MVC based developed application will get divided in 3 components. Each and every component will contain their own code only.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How To Create ASP.NET Core MVC Application?

clock October 11, 2024 08:47 by author Peter

In this article, we will learn how to create an ASP.NET Core MVC web application step by step. Prior to creating the application, let's know about the ASP.NET Core.

What is ASP.NET Core?
ASP.NET Core is an open-source cross-platform framework for developing and building web, cloud, and IoT applications.

Why should we use ASP.NET Core?

  • ASP.NET is an open-source platform that runs on Microsoft .NET Core Framework.
  • We can build and run the ASP.NET core application on a cross-platform environment such as Windows, macOS, Linux, etc.
  • We can build modern apps such as Cloud, IoT, Web apps, mobile backend, etc. and those can be easily enabled to run over the cloud platform.
  • We can host applications on any modern platform such as docker, AKS, or any environment.
  • Saves the efforts of the developer with built-in features such as dependency injection, you can enable docker, containerization, and swagger support in just one click.

Now let's start creating an ASP.NET Core MVC web application.

Step 1. Open Visual Studio.
Open Visual Studio ( I am using 2019)
Once the Visual Studio Opens, Then click on Continue Without Code as shown in the following image.

Then from the Visual Studio Menu, click on File => New Project, as shown in the following image.

Click on the New Project, then the following window appears as shown in step 2.

Step 2. Choose Project Template
You will see the two project templates.

  • ASP.NET Core Web App: This project template creates the web application with Razor pages without a Model, View, or Controller.
  • ASP.NET Core Web App (Model-View-Controller): This project template creates the web application with Model, View, Controller (MVC).

Choose the ASP.NET Core Web App(Model-View-Controller) Template as shown in the following image.

After choosing the project template click on Next.

Step 3. Define Project Name and Location
In the project configuration window, you will see the following options.

  • Project Name: Define any name for your project as per your choice.
  • Location: Choose the location to save the project files on your hard drive of the machine. I have chosen the Project/VS folder of the E drive of the machine, and obviously, it's different on your computer.
  • Solution Name: The solution name is auto-defined based on the project name, but you can change the name based on your own choice.

Additionally, there is a checkbox, if you have checked it, then the solution file (.sln) and project files will be saved in the same folder. Now Choose the minimum details for ease of understanding as shown in the following image.

After defining the required details, click on the Next.

Step 4. Choose the Target Framework
Choose the target framework .NET 5 which is the latest or you can choose based on your requirements, skip the other details for ease of understanding as shown in the following image.

After providing the required details, click the create button. It will create the ASP.NET Core MVC web application as shown in step 5.

Step 5. Understanding ASP.NET Core MVC Folder Structure
The following is the default folder structure of the ASP.NET Core ASP.NET MVC application.

 

Let's understand the preceding project folder structure in brief.

  • The wwwroot folder: The wwwroot is the default root folder for storing the static files related to the project and those files can be accessed programmatically with a relative path.
  • Controller Folder: The controller folder contains the controller classes where the operation-related code is written.
  • Model Folder: The Models Folder contains the domain or entity classes. Models can be written anywhere in the solution such as in a separate class library or folder etc.
  • Views Folder: The Views folder holds the razor pages which are responsible for showing and getting the data from the users.
  • The appsettings.json File: The appsettings.json folder contains the configuration and secret details of the application.
  • Program.cs File: The Program.cs is the starting point of the application which will create the host for an application to run the application.
  • Startup.cs File: The Startup.cs file allows to configuration of the behavior of the application such as defining the routes, dependency injection, etc.

Step 6. Run the ASP.NET Core MVC Application
You can run the application with default contents or let open the Index.cshtml file and put some contents there. Now press F5 on the keyboard or use the run option from Visual Studio to run the application in the browser. After running the application, it will show in the browser as shown in the following image.|



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