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 :: 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 :: Remote Validation in MVC

clock December 12, 2024 07:30 by author Peter

Hello everyone, in this post I will describe how to use MVC to implement remote validation. The technique of remote validation involves publishing data to a server without uploading all of the form data in order to verify particular data. Let's look at a real-world example. I had to verify whether an email address was already in the database for one of my projects. For that, remote validation was helpful; we could validate just the user-provided email address without publishing all the data.


Practical explanation
Let's make an MVC project and give it the appropriate name—in my case, "TestingRemoteValidation." Let's make a model called UserModel that will resemble the project once it has been created.

public class UserModel
{
    [Required]
    public string UserName { get; set; }
    [Remote("CheckExistingEmail","Home",ErrorMessage = "Email already exists!")]
    public string UserEmailAddress { get; set; }
}


Let's get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the name of the action. The second parameter “Home” is referred to as the controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the “Home” controller is called and the third parameter is the error message. Let's implement the “CheckExistingEmail” action result in our home controller.
public ActionResult CheckExistingEmail(string UserEmailAddress)
{
    bool ifEmailExist = false;
    try
    {
        ifEmailExist = UserEmailAddress.Equals("[email protected]") ? true : false;
        return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(false, JsonRequestBehavior.AllowGet);
    }
}

For simplicity, I am just validating the user input with a hard-coded value (
[email protected]) but we can call the database and determine whether or not the given input exists in the database.

Let's create the view using the defined “UserModel” and using the create scaffold template; the UI will look like this.

I hope this will help.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.MVC Core 6 Customized Authentication Filters

clock December 5, 2024 06:47 by author Peter

ASP.NET Core 6's authentication filters offer a strong way to incorporate unique authentication logic. They enable you to verify user credentials, intercept incoming requests, and give or restrict access according to predetermined standards. Here's how to use ASP.NET Core 6 to generate personalized authentication filters.

Create a Custom Authorization Attribute
You can create a custom authorization attribute by extending the AuthorizeAttribute or implementing IAuthorizationFilter or IAsyncAuthorizationFilter.

Example. Custom Attribute for Role-Based Authorization.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    private readonly string _role;
    public CustomAuthorizeAttribute(string role)
    {
        _role = role;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            context.Result = new UnauthorizedResult();
            return;
        }
        if (!user.IsInRole(_role))
        {
            context.Result = new ForbidResult();
            return;
        }
    }
}

How to use it?
[CustomAuthorize("Admin")]
public IActionResult AdminOnlyAction()
{
    return Ok("This is an Admin-only area.");
}


Custom Middleware for Authentication
For more flexibility, you can create custom middleware that inspects HTTP requests and enforces authentication.

Example. Custom Authentication Middleware.
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Threading.Tasks;
public class CustomAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    public CustomAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
        if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
            return;
        }
        var token = authHeader.Substring("Bearer ".Length).Trim();
        // Validate the token (you can use JWT or any other token mechanism)
        if (token != "valid-token") // Replace with your validation logic
        {
            context.Response.StatusCode = StatusCodes.Status403Forbidden;
            await context.Response.WriteAsync("Forbidden");
            return;
        }
        await _next(context); // Pass to the next middleware
    }
}


Register Middleware in Program. cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Add custom authentication middleware
app.UseMiddleware<CustomAuthenticationMiddleware>();
app.MapControllers();
app.Run();

Custom Policy-Based Authorization
Using ASP.NET Core’s policy-based authorization, you can define custom policies for advanced scenarios.

Define a Policy in the Program. cs.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
    {
        policy.RequireClaim("Role", "Admin");
    });
});
var app = builder.Build();


Apply policy
[Authorize(Policy = "AdminOnly")]
public IActionResult AdminOnlyAction()
{
    return Ok("This is an Admin-only area.");
}


Add Custom Authorization Logic by Handler.
Create a custom requirement and handler
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using System.Threading.Tasks;
public class CustomRoleRequirement : IAuthorizationRequirement
{
    public string Role { get; }
    public CustomRoleRequirement(string role)
    {
        Role = role;
    }
}
public class CustomRoleHandler : AuthorizationHandler<CustomRoleRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        CustomRoleRequirement requirement)
    {
        if (context.User.HasClaim(c => c.Type == ClaimTypes.Role && c.Value == requirement.Role))
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}


Register the handler in services.
builder.Services.AddSingleton<IAuthorizationHandler, CustomRoleHandler>();

  • Use custom attributes for lightweight authorization checks.
  • Implement custom middleware for broader authentication handling.
  • Use policy-based authorization for flexible and reusable rules.


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 :: How to Use Single Sign-On for your ASP.NET MVC Application?

clock November 13, 2024 08:44 by author Peter

Implementing Single Sign-On (SSO) for ASP.NET MVC applications provides a seamless, hassle-free login experience for your users, regardless of whether you're creating SaaS apps or an educational platform.


However, how can SSO improve security and streamline user authentication?
We'll go over SSO's specifics, the advantages of integrating it with ASP.NET MVC applications, and how it can streamline and manage your authentication procedure in this article.

What is Single Sign-On (SSO)?
Single Sign-On (SSO) has become a must-have for modern web applications. It lets you log in once and access many different applications without having to type in your username and password each time. This not only makes logging in easier but also helps keep your accounts safer by reducing password issues.

If you’re working on an ASP.NET MVC app, adding SSO can really help with user management, especially in big companies where quick access to different systems is crucial.

Here’s how it works:
When a user wants to access secure parts of your app, they just enter their username and password once. If they need to use other related applications, they usually have to enter their info again and again.

But with SSO, you only need to sign in once to get access to all connected services. As the name implies, you’re only asked to log in once during a specific time period before your login session expires.

What Are the Types of SSO Protocols?

For Single Sign-On (SSO) to work smoothly, Service Providers (SP) and Identity Providers (IDP) need to agree on a common way to share identity and login information. Here are some of the main protocols they use:

OAuth (Open Authorization)

OAuth is a widely used standard that helps with token-based authentication. It allows users to share their account information with third-party services without giving away their passwords. Instead of sharing your password, OAuth acts as a middleman. It gives the service an access token, which lets them see only certain account details.

OpenID

OpenID is another popular authentication protocol used by major companies like Google and Facebook. It’s an open and decentralized standard. With OpenID, third-party Identity Providers help verify users for Relying Parties (RP). Think of it as an extra layer on top of OAuth, making it even more secure.

SAML (Security Assertion Markup Language)

SAML works by using session cookies in your web browser. This lets you access specific pages without needing to log in each time. It gives companies more control to keep their SSO logins secure. For a more detailed look at SAML, check out the information below.

Where Can We Use SAML SSO?

SAML SSO is mainly used for authentication. This means that different apps, websites, and services need to trust the SSO site to let you access and edit your data.

Here’s how it works:
When you want to access something on a service provider’s app, you first need to log in with your username and password. If you’ve done this before, getting in is easier! The app sends a request to authenticate you, and then the identity provider sends back a response to confirm you’re good to go.

SAML is handy, especially when a service provider offers their features across various applications. It even opens up opportunities for third-party apps to use the same data in their own unique ways.

For example:

  • Websites that provide data stats for online multiplayer games.
  • Social media apps and forums that share a common topic.
  • Online video streaming platforms that engage viewers.
  • Software marketplaces like Steam that track user analytics


Why is SAML SSO Great for ASP.NET MVC Applications?
SAML SSO is highly effective for ASP.NET MVC applications for several reasons. First, it boosts security so you can feel safe while using your apps. It also helps manage user identities in one place, making it easier for everyone.

With SAML SSO, users only need to log in once to access multiple applications, which saves time and hassle. Plus, it works well across different domains, meaning you can easily connect with other services.

For businesses with complicated authentication needs, SAML SSO offers great flexibility and meets compliance requirements. It’s also scalable, so as your business grows, it can keep up. Overall, SAML SSO provides a secure and easy-to-use login experience for both users and administrators.
What are the Benefits of Using ASP.NET MVC Single Sign-On?

Faster Development
Using ASP.NET MVC Single Sign-On (SSO) helps developers save time. With a common authentication framework, they can get things done quicker. Plus, if the SSO system works independently, it takes even more pressure off the developers.

Lower Costs
Shorter development time means lower costs. It is a success when developers spend less time building. Also, fewer users forget their passwords or call the IT help desk for assistance, which cuts down on overall expenses.

Better Security
One of the best things about SSO is that it makes users less likely to fall for phishing attacks. SSO also makes sure that users connect through secure channels. This way, only one place handles their login info. The apps themselves only get a simple signal to let the user in or not. This means less sensitive information is shared.

Easier Administration
Managing user accounts becomes much easier with SSO. It reduces the workload for administrators because they don’t have to handle multiple logins. Just remember, SSO only deals with who can log in. Deciding what users can access based on their permissions still needs to be set up separately.

Better User Experience
With ASP.NET MVC Single Sign-On, users only need to log in once. They won’t have to keep entering their usernames and passwords for different applications and browsers, making everything smoother and simpler.

Conclusion

Integrating Single Sign-On (SSO) into your ASP.NET MVC application can really boost both security and user experience. With SSO, users only need to log in once to access multiple systems. This not only reduces the hassle of remembering multiple passwords but also helps organizations manage identities more effectively.

By following the steps in this guide, you can easily set up SSO for your ASP.NET MVC app. Just remember to test everything thoroughly, pick the right identity provider, and make sure your authentication flow fits your business needs. With a solid SSO solution in place, you can enhance your application's security and make it easier for users to navigate.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Entity Framework with ASP.NET MVC, Database-First

clock November 1, 2024 06:46 by author Peter

Upon writing multiple articles on this website, I discovered that nearly all of them required me to build up an example application linked to an entity framework in order to access the database. Additionally, each time, I had to start over with the setup procedure so that a new reader could easily follow along. Even when I introduced a really basic idea like caching, I had to spend 80% of my time configuring the sample application and only 20% of my time explaining the caching concept.

As a result, I believe it is preferable to create a fundamental model, such as an entity framework sample, for each technique, which I can then reuse as needed. I established a list of the series of articles below, and I will write them one by one, while the Entity framework overview and concept will be addressed in article (0).

Note
We write the Entity Framework for MVC module, but the pattern is the same or similar when applying to Web Application or Web API.

Introduction

This article is about Entity Framework with .Net MVC, Database-First approach.  This will be the easist and convenient one in the whole six approaches.

We will make a sample app step by step,

  • Step 1: Create an ASP.NET MVC application
  • Step 2: Reverse Engineer Model
  • Step 3: Create Controller to access data from entity framework
  • Step 4: Run the app

At the end, we will have an .Net MVC app that can consume a database directly through entity framework.

Step 1 - Create an ASP.NET MVC app

We use the current version of Visual Studio 2019 16.9.3 and .NET Framework 4.8 to build the app:

  • Start Visual Studio and select Create a new project.
  • In the Create a new project dialog, select ASP.NET Web Application (.NET Framework) > Next.
  • In the Configure your new project dialog, enter MVC_DatabaseFirst for Project name > Create.
  • In the Create a new ASP.NET Web Application dialog, select MVC > Creat

Note
For biginners, you may see details from here. Build and run the app, you will see the following image shows the app,

Step 2, Reverse Engineer Model
We’re going to make use of Entity Framework Designer, which is included as part of Visual Studio, to create our model.

  • Project -> Add New Item…
  • Select Data from the left menu and then ADO.NET Entity Data Model

Enter StoreModel as the name and click Add
This launches the Entity Data Model Wizard

Select Generate from Database and click Next.

In the Choose Your Data Connection Dialog box, Click New Connection.

In the Connection Properties Dialog box, Choose Server Name: Localhost, and Select or Enter database name: Pubs, Click OK.

You got connection string, Click Next.

Click Next.

Click the checkbox next to ‘Tables’ to import stores and click Finish. Once the reverse engineer process completes the new model is added to your project and opened up for you to view in the Entity Framework Designer (StoreModel.edmx):

The created class Store like this (StoreModel.edmx/StoreModel.tt/store.cs)
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MVC_DatabaseFirst
{
    using System;
    using System.Collections.Generic;

    public partial class store
    {
        public string stor_id { get; set; }
        public string stor_name { get; set; }
        public string stor_address { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string zip { get; set; }
    }
}

The Data Context will be in pubsEntities class (StoreModel.edmx/StoreModel.Context.tt/StoreModel.Context.cs):
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace MVC_DatabaseFirst
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class pubsEntities : DbContext
    {
        public pubsEntities()
            : base("name=pubsEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<store> stores { get; set; }
    }
}


and the connection details for the database will be inserted into web.config file:
<connectionStrings>
  <add name="pubsEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=pubs;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>

Step 3:  Create Controller to access data from entity framework
From Visual Studio IDE,

  • Right-click the Controllers folder.
  • Select Add > New Scaffolded Item Or Controller to open the window Add New Scaffolded Item
  • In the Add New Scaffold Item dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.;
  • In the Add Controller dialog box,
    • Select store (MVC_DatabaseFirst) for the Model class.
    • Select pubsEntities (MVC_DatabaseFirst) for the Data context class.
    • For the Controller name enter storesController.
    • Click Add.  

Step 4: Run the app
Type domain/stores into the link, you will get:



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



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Get Version of Your MVC Application?

clock October 3, 2024 08:37 by author Peter

This article shows how to determine what version of ASP.NET MVC is being used in your existing MVC application.At Runtime

There are the following two ways to get the version of your MVC application.

  • At design time
  • At runtime

At design time
To get the version of your MVC application at design time use the following procedure.
Go to the project in the Solution Explorer.

Expand references.

Right-click on "System.Web.Mvc" and select properties.

Now you will see the version property.

At Runtime
To get the version of your MVC you can use the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCVersion.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/

        public string Index()
        {
            return "<b>Version of your MVC is: " + typeof(Controller).Assembly.GetName().Version.ToString() + "</b>";
        }

    }
}

typeof(Controller)
    .Assembly
    .GetName()
    .Version
    .ToString()

The preceding line of code provides the version of your MVC.

Output



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Stopping Denial-of-Service Attacks in ASP.NET Core MVC Programs

clock September 10, 2024 08:21 by author Peter

An ASP.NET Core MVC application can be protected against DoS (Denial of Service) attacks by implementing a number of solutions, each of which addresses a different component of possible vulnerability. These are the standard methods.


1. Throttling and rate limitation

  • Rate limitation stops malevolent users from flooding the server with requests by restricting the amount of requests a client can make in a certain amount of time.
  • Rate limitation can be implemented by middleware or third-party libraries such as AspNetCoreRateLimit.

Using AspNetCoreRateLimit as an example
dotnet add package AspNetCoreRateLimit

Configure it in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    services.Configure<IpRateLimitOptions>(options =>
    {
        options.GeneralRules = new List<RateLimitRule>
        {
            new RateLimitRule
            {
                Endpoint = "*",
                Limit = 1000,
                Period = "5m"
            }
        };
    });
    services.AddInMemoryRateLimiting();
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseIpRateLimiting();
}


2. Request Size Limiting
Limit the size of requests to prevent large payloads from being used to exhaust server resources.

In Program.cs or Startup.cs
services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = 10 * 1024; // Set limit to 10KB
});

services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024; // 10KB
});


3. Timeout Configuration
Set proper timeout values for requests to avoid long-running connections that could hog resources.

In Startup.cs
services.AddHttpClient("myClient")
    .SetHandlerLifetime(TimeSpan.FromMinutes(5)) // Set handler timeout
    .AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10))); // Set HTTP request timeout


4. Input Validation

Properly validate user input to avoid potential DoS vulnerabilities caused by computational complexity or resource exhaustion.

  • Validate the length, type, and format of input.
  • Reject large or malformed data early in the request pipeline.

5. Captcha for Forms
Add CAPTCHAs (e.g., Google reCAPTCHA) to critical forms (login, registration, etc.) to prevent automated bots from generating large numbers of requests.
dotnet add package reCAPTCHA.AspNetCore
Configure in Startup.csservices.AddRecaptcha(options =>
{
    options.SiteKey = "your-site-key";
    options.SecretKey = "your-secret-key";
});
6. Distributed Caching for Load Balancing
Use caching to reduce the load on your server, thus preventing resource exhaustion. You can implement caching using MemoryCache, Redis, or NCache.Example using MemoryCacheservices.AddMemoryCache();

7. Use CDN for Static Resources

Offload static resources (images, CSS, JavaScript) to a Content Delivery Network (CDN) to reduce server load.

8. Web Application Firewall (WAF)

Use a WAF to inspect and filter traffic before it reaches your application. WAFs can block suspicious IP addresses, filter out malformed requests, and provide additional security against attacks.

9. Client-Side Caching

Implement proper cache headers to reduce unnecessary server requests by allowing browsers to cache resources.

10. HTTP/2 and Keep-Alive Settings

Tune server settings to prevent resource exhaustion. Ensure HTTP/2 is enabled, which multiplexes requests, and configure Keep-Alive settings.

Example in Startup.cs
services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
});

Now we will implement the complete project for this article.

Step 1. Create a New ASP.NET Core MVC Project

Create a new ASP.NET Core MVC project via the.NET CLI or Visual Studio.
dotnet new mvc -n DoSAttackPrevention
cd DoSAttackPrevention
Step 2. Install Required NuGet PackagesInstall the necessary NuGet packages.
dotnet add package AspNetCoreRateLimit
dotnet add package reCAPTCHA.AspNetCore
Step 3. Configure Services in Startup.csModify Startup.cs to include the middleware and services.using AspNetCoreRateLimit;
using Microsoft.AspNetCore.HttpOverrides;
using reCAPTCHA.AspNetCore;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC
        services.AddControllersWithViews();

        // Memory Cache for Rate Limiting
        services.AddMemoryCache();

        // Configure Rate Limiting Options
        services.Configure<IpRateLimitOptions>(options =>
        {
            options.GeneralRules = new List<RateLimitRule>
            {
                new RateLimitRule
                {
                    Endpoint = "*",
                    Limit = 100,
                    Period = "1m" // 100 requests per minute per IP
                }
            };
        });

        services.AddInMemoryRateLimiting();
        services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

        // Add Recaptcha Service
        services.AddRecaptcha(options =>
        {
            options.SiteKey = "your-site-key";
            options.SecretKey = "your-secret-key";
        });

        // Configure Request Size Limit
        services.Configure<IISServerOptions>(options =>
        {
            options.MaxRequestBodySize = 10 * 1024; // 10 KB
        });

        services.Configure<KestrelServerOptions>(options =>
        {
            options.Limits.MaxRequestBodySize = 10 * 1024; // 10 KB
        });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

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

        app.UseRouting();

        app.UseIpRateLimiting(); // Apply Rate Limiting

        app.UseAuthorization();

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


Step 4. Add Rate Limiting Configuration

In the appsettings.json file, add rate-limiting options.
{
  "IpRateLimit": {
    "EnableEndpointRateLimiting": true,
    "StackBlockedRequests": false,
    "HttpStatusCode": 429,
    "RealIpHeader": "X-Real-IP",
    "ClientIdHeader": "X-ClientId",
    "GeneralRules": [
      {
        "Endpoint": "*",
        "Period": "1m",
        "Limit": 100
      }
    ]
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Step 5. Implement CAPTCHA in a Form (e.g., Login Form)
In the Login View (Views/Home/Login.cshtml), implement Google reCAPTCHA.
@using reCAPTCHA.AspNetCore
@inject IRecaptchaService _recaptcha
@{
    var recaptchaResult = await _recaptcha.Validate(Request);
}

<form asp-controller="Home" asp-action="Login" method="post">
    <div class="form-group">
        <label for="Username">Username</label>
        <input type="text" class="form-control" id="Username" name="Username" required>
    </div>
    <div class="form-group">
        <label for="Password">Password</label>
        <input type="password" class="form-control" id="Password" name="Password" required>
    </div>

    <!-- Google reCAPTCHA -->
    <div class="g-recaptcha" data-sitekey="your-site-key"></div>

    <button type="submit" class="btn btn-primary">Login</button>
</form>

@section Scripts {
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
}

Step 6. Handle CAPTCHA Validation in the Controller

In the HomeController (Controllers/HomeController.cs), validate the CAPTCHA.using Microsoft.AspNetCore.Mvc;
using reCAPTCHA.AspNetCore;

public class HomeController : Controller
{
    private readonly IRecaptchaService _recaptcha;

    public HomeController(IRecaptchaService recaptcha)
    {
        _recaptcha = recaptcha;
    }

    [HttpPost]
    public async Task<IActionResult> Login(string username, string password)
    {
        var recaptchaResult = await _recaptcha.Validate(Request);
        if (!recaptchaResult.success)
        {
            ModelState.AddModelError(string.Empty, "CAPTCHA validation failed.");
            return View();
        }

        // Perform login logic here (e.g., validate username/password)

        return RedirectToAction("Index");
    }

    public IActionResult Index()
    {
        return View();
    }
}
Step 7. Implement Input Validation
Ensure that proper validation is applied to forms. For example, in the login form above, you can add validation attributes in the model or controller.
[Required]
[MaxLength(50)]
public string Username { get; set; }
[Required]
[MinLength(6)]
public string Password { get; set; }


Step 8. Configure Caching (Optional)
You can implement caching to reduce server load.services.AddMemoryCache();

Step 9. Build and Run the Project
You can now run the project.dotnet run
The project demonstrates rate limiting, request size limiting, and CAPTCHA integration, which are essential measures to prevent DoS attacks. You can extend this further by adding distributed caching (e.g., Redis) and a WAF.



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