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



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Attribute Routing Overview in MVC and .NET Core

clock September 4, 2024 08:36 by author Peter

Attribute routing is a potent feature in ASP.NET Core that lets you explicitly define routing information on controller activities. Compared to traditional routing, this offers more flexibility and control over how HTTP requests are routed to your API endpoints. This is a summary of attribute routing's functions and how to use it in your.NET Core API.


Attribute Routing: What is It?

With attribute routing, you may use attributes to construct routes directly on your action methods or controllers. This method can help make routing easier to comprehend and control because it is more explicit.

How to use Attribute Routing?
1. Basic Attribute Routing

You can apply routing attributes directly to action methods and controllers. For example.

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // GET api/products
    [HttpGet]
    public IActionResult GetAllProducts()
    {
        // Implementation
    }
    // GET api/products/5
    [HttpGet("{id}")]
    public IActionResult GetProductById(int id)
    {
        // Implementation
    }
    // POST api/products
    [HttpPost]
    public IActionResult CreateProduct([FromBody] Product product)
    {
        // Implementation
    }
}


Controller Route: [Route("api/[controller]")] sets the base route for all actions in the controller. [controller] is a placeholder that gets replaced with the name of the controller (e.g., Products).
Action Routes: [HttpGet], [HttpGet("{id}")], [HttpPost] specify the HTTP methods and the routes for the actions.

2. Route Parameters
You can use route parameters in the attribute routing to capture values from the URL.

[HttpGet("search/{query}")]
public IActionResult SearchProducts(string query)
{
    // Implementation
}

Route Parameter: {query} in the route template will capture the value from the URL and pass it to the action method.

3. Optional Parameters
To make route parameters optional, use the following syntax.
[HttpGet("items/{id?}")]
public IActionResult GetItemById(int? id)
{
    // Implementation
}


Optional Parameter: {id?} makes the id parameter optional.

4. Route Constraints
You can add constraints to route parameters to enforce specific patterns.
[HttpGet("products/{id:int}")]
public IActionResult GetProductById(int id)
{
    // Implementation
}

Route Constraint: {id:int} ensures that the id parameter must be an integer.

5. Route Prefixes and Constraints at Controller Level
You can also set route prefixes and constraints at the controller level.
[ApiController]
[Route("api/[controller]/[action]")]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAllOrders()
    {
        // Implementation
    }

    [HttpGet("{id:int}")]
    public IActionResult GetOrderById(int id)
    {
        // Implementation
    }
}

Action Route: [action] is replaced with the action method name in the route URL.

6. Combining Routes
You can combine routes and use route templates to create complex routing scenarios.
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
    [HttpGet("{customerId}/orders/{orderId}")]
    public IActionResult GetCustomerOrder(int customerId, int orderId)
    {
        // Implementation
    }
}

Benefits of Attribute Routing
Clarity and Control: Route definitions are more explicit and closely related to their corresponding actions, making it easier to understand and manage routes.
Flexibility: Allows for more complex routing scenarios, including optional and default parameters, constraints, and combined routes.
Customization: Facilitates precise control over route templates and endpoints.

Combined Route
The route combines customerId and orderId parameters to define a more specific endpoint.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: How to Centralize Modal Popups in .NET MVC to Simplify Code and Enhance?

clock August 26, 2024 06:55 by author Peter

Several forms to manage modal popups can result in repetitive code and more maintenance work. We'll look at how to centralize modal popup code in a.NET MVC application in this blog post. This will let you define the modal once and utilize it in other places in your project. We will cover how to create a modal's partial view, add it to various sites, and effectively handle modal triggers. You will have a better structured and manageable method for dealing with modal popups in your.NET MVC apps at the end of this article.


You can centralize the modal popup code and utilize it throughout your application to avoid repeating it in every form. Here's how to go about it.

Establish a Partial Model View
The modal code can be included in a partial view that you design. You can add this partial view to any page that requires a modal.

Steps
Create Partial View
Right-click on the Views/Shared folder (or any other folder) and select Add -> View.
Name the view _DeleteModal.cshtml.
In the view, add the modal code.

    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <asp:Label ID="ltrlDelHead" Text="Are You Sure, You want to Delete This?" runat="server"></asp:Label>
                </h5>
                <button type="button" class="bootbox-close-button close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>
            <div class="modal-body">
                <div class="bootbox-body">
                    <div class="bootbox-form"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button>
                <asp:LinkButton ID="lnkRecordDelete" class="btn bg-danger" runat="server" OnClick="lnkRecordDelete_Click">Delete</asp:LinkButton>
            </div>
        </div>
    </div>

Include Partial View in Your Pages
In any view where you want to use this modal, simply include the partial view.
@Html.Partial("_DeleteModal")


Alternative Using Layout or Master Page
If you need this modal on many pages, you can add the modal code directly to your layout or master page so it’s available throughout your application.

Steps

Open your Layout.cshtml (or master page if using WebForms).
Add the modal code before the closing </body> tag.

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
   @Html.Partial("_DeleteModal")
</div>


Then, use JavaScript or server-side logic to trigger this modal when needed.

Triggering the Modal
To trigger the modal from different parts of your application, you can use JavaScript or server-side code to open it when required.
$('#deleteModal').modal('show');

This approach centralizes the modal code, making your application more maintainable and easier to manage. Now, you only need to update the modal in one place if any changes are required.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Learn About Action Selectors In ASP.NET MVC

clock August 13, 2024 08:42 by author Peter

Nearly all of the information you need to know about action selectors in ASP.NET MVC action methods is covered in this article. I'm producing this post to explain to you the most important, fundamental, and advanced ideas of action selectors.

Overview and Context
The characteristics that can be added to action methods to affect the choice of action method are known as action selectors. Which action methods are called in response to an HTTP request are determined by action selectors. As you may have observed in my earlier post, "MVC Architecture and its Pipeline," under the "Pipeline in MVC" section, the HTTP request first reaches "Routing," then "Controller Initialization," and finally "Action Execution." The rendering of the view is thereby limited to the "Result Execution." Action selectors are used in the section titled "Action Execution" and are crucial in determining which action method is best for handling a given HTTP request. Now let's examine action methods.

Which action methods are there?
The controller's action methods are those whose names must coincide with the method names in the request URL. Following the execution of the request, these methods produce the response. A controller may have numerous action methods. Additionally, you can designate a controller's default action method for handling requests.

What do you mean by action selectors?
A certain action method needs to be chosen in the answer to a request sent to the routing engine. Therefore, action selectors are in charge of choosing this course of action. Because of the attribute applied above the action method, the action selector does its job. Let's examine the many kinds of action selectors.

Types of action selectors
There are three types of action selectors

  • NonAction
  • ActionName
  • ActionVerbs

Name of Action
An action selector called the [ActionName] attribute is used to change the name of the action method. When we want that action method to be called by a different name than the method's real name, we utilize the [ActionName] attribute. The example that follows shows you how to use an action method that was originally named "Time." Let's make the ActionSelectorsDemo project. Choose "Visual C#," then "ASP.NET Web Application," then give the project a name and click "OK."

Select “Empty” and mark “MVC” then click OK, as shown below.

The project is created successfully. Now, create a Controller as shown below.

Select the type of Controller as “MVC 5 Controller – Empty” and click “Add”.

Then, give the name of the Controller and click “Add”.

Make the following changes in the Index action method of the HomeController, as shown below in the screenshot.

Now, the project is ready to take a look at a practical example of [ActionName] action selector. Now, let’s add an action method with the name of “Time” whose purpose is to print the current time. See the code below.

public String Time() {
    return @"Current Time is: " + DateTime.Now;
}

When you build and run the application with this /Home/Time URL, you should see the following output.

Now we are going to use the [ActionName] attribute with the “Time” action method. See the code below.
[ActionName("GetTime")]
public String Time() {
    return @"Current Time is: " + DateTime.Now;
}

Now build and run the application with this /Home/Time URL, you should see the following error, it is because of the [ActionName] action selector.

By using this action selector, you have changed the name of the action method, now the URL /Home/GetTime only works instead of /Home/Time. See the output below.

Hence you have seen that the [ActionName] action selector can change the name of the action method.

NonAction

[NonAction] attribute is an action selector that indicates a public method of the controller is not an action method. We use the [NonAction] attribute when we want a method that shouldn’t be treated as an action method.

As you know, the Controller contains the methods that are public and are termed action methods because of one-to-one mapping with the HTTP-requested URL. But when you want that, any method of Controller shouldn’t be treated as an action method, then you have to use the [NonAction] attribute.

Example
Now let’s make some changes in the HomeController of ActionSelectorsDemo project. Add another method named “GetTimeMethod” whose responsibility is also to print the current time. And then call this newly added method into the “Time” action method. You can see the code of both action methods below.
[ActionName("GetTime")]
public String Time() {
    return GetTimeMethod();
}
public String GetTimeMethod() {
    return @"Current Time is: " + DateTime.Now;
}


Now observe the output, after building and running the application. When we run the application with this /Home/Time URL, we’ll see an error because we are bound to use the name “GetTime” for this action method because of the [ActionName] action selector. Now when you run the application with this /Home/GetTimeMethod, you should see the output given below.

As you have seen, you are still able to access GetTimeMethod while there is no need to access it because it is producing the same output as produced by the “GetTime” action method. So we need to restrict its access by using the [NonAction] action selector because it makes the method a non-action method. So it can’t be called in the request URL at all. Let’s see its example. The code of the “GetTimeMethod” method will become as follows.

[NonAction]
public String GetTimeMethod() {
    return @ "Current Time is: " + DateTime.Now;
}


So the output will become.


So as you have seen, the [NonAction] action selector is used to make an action method Non-Action method.

ActionVerbs

You have seen in the beginning of this article what actions are. And you should also know “Verbs” which are defined as “words which are used to describe an action, state or occurrence of an event”. So as the name suggests, “ActionVerbs” can be defined as “the words that describe the action, purpose, and state of the action method of a Controller”. Now, let’s move towards its technical explanation.

When an HTTP request comes to the controller on a specific action method, then this selector helps us to select the correct action method based on the HTTP requested method. It also helps us to create more than one action method with the same name, also referred to as overloading. So to differentiate these action methods, we use action verbs. We’ll see its example later in this article.

MVC framework supports different ActionVerbs, shown as follows.

  • HttpGet: It is used to get information from the server. When this applies to the action method, it restricts the action method to accept only HTTP GET requests.
  • HttpPost: It is used to post information on the server. When this applies to the action method, it restricts the action method to accept only HTTP POST requests.
  • HttpPut: It is used to create or replace existing information on the server, but can’t update. And when this applies to the action method, it restricts the action method to accept only HTTP PUT requests.
  • HttpDelete: It is used to delete any existing information from the server. When this applies to an action method, it restricts the action method to accept only HTTP Delete requests.
  • HttpPatch: It is used to fully or partially update any existing information on the server. When this applies to the action method, it restricts the action method to accept only HTTP Patch requests.
  • HttpOptions: It is used to represent information about the options of the communication that are supported by the web server.


Action verbs are very popular in using APIs. In the MVC framework, if you don’t apply any attribute of the action selector on the top of the action method when the method is called from the HTTP request, then that HTTP request will behave like a HttpGet request by default.

Conclusion
I hope this article has helped you understand all the concepts of action selectors in ASP.NET MVC. And stay tuned for my next article. If you have any queries then feel free to contact me in the comments section. Also, giving feedback, either positive or negative, will help me to make my articles better and increase my enthusiasm to share my knowledge.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Behavior of Session States Per Action in ASP.NET MVC

clock July 25, 2024 09:28 by author Peter

We can regulate the session state behavior in ASP.NET MVC with the aid of the SessionState Attribute. Using this property, we may set the session state to read-only, required, or disabled for the controller. We can only use this attribute at the controller level because it is a class level attribute. A controller's action methods may behave differently from the controller session state behavior in some cases. The following solution is quite helpful in this situation. Thus, in ASP.NET MVC, we may implement a session state behavior for each action.

Problem Synopsis
The SessionState property allows us to regulate the behavior of the session state, however it is only applicable at the controller level. This indicates that the session state behavior is the same for all of the controller's action methods. What is the course of action to take now that certain controller action methods do not require a session while others do?

Resolution
In this case, all the action methods that share the same session state behavior can be moved to a distinct controller class and made. This is a poor course of action. Alternatively, we may override the session state behavior for that particular action method by creating a custom action property.


To create a custom action attribute that overrides the session state's behavior, follow these steps.

First, make a custom attribute.

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]  
    public sealed class ActionSessionStateAttribute : Attribute  
    {  
        public SessionStateBehavior Behavior { get; private set; }   
        public ActionSessionStateAttribute(SessionStateBehavior behavior)  
        {  
            this.Behavior = behavior;  
        }  
    } 


Step 2: Create custom controller factory
    public class CustomControllerFactory : DefaultControllerFactory  
    {  
        protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)  
        {  
            if (controllerType == null)  
            {  
                return SessionStateBehavior.Default;  
            }  
            var actionName = requestContext.RouteData.Values["action"].ToString();  
            MethodInfo actionMethodInfo;  
            actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);  
            if (actionMethodInfo != null)  
            {  
                var actionSessionStateAttr = actionMethodInfo.GetCustomAttributes(typeof(ActionSessionStateAttribute), false)  
                                    .OfType<ActionSessionStateAttribute>()  
                                    .FirstOrDefault();  
       
                if (actionSessionStateAttr != null)  
                {  
                    return actionSessionStateAttr.Behavior;  
                }  
            }  
            return base.GetControllerSessionBehavior(requestContext, controllerType);  
        }  
    }  


Step 3: Register custom controller factory in Global.asax
    protected void Application_Start()  
    {  
        AreaRegistration.RegisterAllAreas();  
        RegisterGlobalFilters(GlobalFilters.Filters);  
        RegisterRoutes(RouteTable.Routes);  
        ControllerBuilder.Current.SetControllerFactory(typeof(CustomControllerFactory));  
    }

Step 4: Attribute usages
    [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]    
    public class HomeController : Controller    
    {    
        public ActionResult Index()    
        {    
            ViewBag.Message = "Welcome to ASP.NET MVC!";    
            TempData["test"] = "session less controller test";    
            return View();    
        }  
        [ActionSessionState(System.Web.SessionState.SessionStateBehavior.Required)]    
        public ActionResult About()    
        {    
            Session["test"] = "session less controller test";    
            return View();    
        }    
    }




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Sorting Results in ASP.NET Core MVC

clock July 12, 2024 06:43 by author Peter

An action method in ASP.NET Core MVC can return many kinds of outcomes, which are referred to as Action outcomes. What kind of response the controller delivers back to the client is determined by these outcomes. The standard technique for returning results from a controller action method is defined by the IActionResult interface. Let's examine the many kinds of results.

1. ViewResult
This result is used to render a view (HTML page) to the client. It is the most common type used in MVC applications.

Example
public IActionResult Index()
{
    return View();
}

2. JsonResult

This result is used to return JSON-formatted data. It is commonly used for API responses.

Example
public JsonResult GetJsonData()
{
    var data = new { Name = "John", Age = 30 };
    return Json(data);
}

3. ContentResult

This result is used to return plain text or any other content.

Example
public ContentResult GetContent()
{
    return Content("Hello, this is plain text.");
}


4. FileResult

This result is used to return a file to the client, such as a document, image, or any other file.

Example
public FileResult GetFile()
{
    var fileBytes = System.IO.File.ReadAllBytes("path/to/file.pdf");
    return File(fileBytes, "application/pdf", "download.pdf");
}


5. RedirectResult

This result is used to redirect the client to a specified URL.

Example
public RedirectResult RedirectToUrl()
{
    return Redirect("https://www.example.com");
}

6. RedirectToActionResult
This result is used to redirect the client to a specific action method in the controller.

Example
public RedirectToActionResult RedirectToActionMethod()
{
    return RedirectToAction("Index", "Home");
}


7. RedirectToRouteResult
This result is used to redirect the client to a specific route.

Example
public RedirectToRouteResult RedirectToRouteMethod()
{
    return RedirectToRoute(new { controller = "Home", action = "Index" });
}


8. StatusCodeResult
This result is used to return a specific HTTP status code.

Example
public StatusCodeResult GetStatusCode()
{
    return StatusCode(404);
}


9. EmptyResult

This result does not return any content.

Example
public EmptyResult DoNothing()
{
    return new EmptyResult();
}


10. PartialViewResult
This result is used to render a partial view.

Example
public PartialViewResult GetPartialView()
{
    return PartialView("_PartialView");
}


11. ObjectResult

This result is used to return an object as the response. It is often used in APIs to return data along with an HTTP status code.

Example
public ObjectResult GetObject()
{
    var data = new { Name = "John", Age = 30 };
    return new ObjectResult(data) { StatusCode = 200 };
}


Conclusion

ASP.NET Core MVC provides a rich set of action results that allow you to return various types of responses from your controller actions. Each result type serves a specific purpose and can be used to meet the requirements of different scenarios. Understanding these result types is crucial for building robust and flexible web applications.

With these action results, you can efficiently manage how your application responds to client requests, whether it's rendering views, returning JSON data, or handling file downloads.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Managing CRUD Operations in ASP.NET MVC with Razor and C#

clock July 4, 2024 09:56 by author Peter

Creating, reading, updating, and deleting (CRUD) operations are essential functionalities for any web application. In this article, we'll explore how to implement these operations in an ASP.NET MVC application using Razor views and C#.


Controller Actions

Democurd Action
The democurd action is responsible for displaying a list of democurd records.

public ActionResult democurd()
{
    DemoModel model = new DemoModel();
    model.Id = Convert.ToInt32(Session["Id"]);
    var list = demovider.Getdemocurd(model);
    return View(list);
}

  • Initialization: A DemoModel object is created and its Id property is set from a session variable.
  • Data Fetching: The Getdemocurd method of demovider is called to fetch a list of democurd records.
  • Return View: The list of records is passed to the view for display.

democurdAddEdi Action (GET)
The democurdAddEdi action displays a form for adding or editing a democurd record.
public ActionResult democurdAddEdi()
{
    democurdinput model = new democurdinput();
    return View(model);
}

    Model Initialization: A new democurdinput model is initialized.
    Return View: The model is passed to the view for rendering the form.

democurdAddEdi Action (POST)
This action handles the form submission for adding or editing a democurd record.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> democurdAddEdi(democurdinput obj)
{
    try
    {
        if (ModelState.IsValid)
        {
            // Your logic here
            return RedirectToAction("StationMaster");
        }
        else if (obj.StationId != 0)
        {
            var Li = democurdAddvider.democurdAdd(obj);
            if (Li.Status == "0")
            {
                return RedirectToAction("democurd");
            }
            else
            {
                return View(obj);
            }
        }
    }
    catch (Exception ex)
    {
        // Handle exception
    }

    return View(obj);
}

  • Form Validation: Checks if the model state is valid.
  • Condition Handling: Depending on the StationId, it either redirects or returns the view with validation errors.
  • Exception Handling: Catches and handles any exceptions that occur during the process.

Editdemocurd Action

The Editdemocurd action fetches a democurd record for editing.
public ActionResult Editdemocurd(int? id)
{
    democurdinput model = new democurdinput();
    try
    {
        model.dmId = Convert.ToInt32(id);
        var list = democurdvider.Getdemocurd(model);
        var ass = list.FirstOrDefault();
        return PartialView("StationMasterAddEdi", ass);
    }
    catch (Exception ex)
    {
        // Handle exception
    }
    return View("democurdAddEdi", null);
}

    Model Initialization: A new democurdinput model is initialized with the id parameter.
    Data Fetching: Retrieves the record to be edited using the Getdemocurd method.
    Return Partial View: The record is passed to a partial view for editing.

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="card-title">
                        <i class="icon-layers"></i> Manage democurd
                        <span class="pull-right">
                            <a href="@Url.Action("methodname", "controllername")" class="btn btn-primary mt-ladda-btn ladda-button btn-circle" data-style="expand-right">
                                <span class="ladda-label">
                                    <i class="fa fa-plus"></i> Add
                                </span>
                            </a>
                        </span>
                    </div>
                    <div class="preview-list">
                        <table class="table table-striped table-bordered dt-responsive nowrap" id="dataTableModules1">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Number</th>
                                    <th>val</th>
                                    <th>valtude</th>
                                    <th>status</th>
                                    <th>StatusDesc</th>
                                    <th>wstg</th>
                                    <th class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var i in Model)
                                {
                                    <tr>
                                        <td>@i.Name</td>
                                        <td>@i.Number</td>
                                        <td>@i.val</td>
                                        <td>@i.valtude</td>
                                        <td>@i.status</td>
                                        <td>@i.StatusDesc</td>
                                        <td>@i.wstg</td>
                                        <td class="text-center">
                                            <a href="@Url.Action("Editdemocurd", "Master", new { id = @i.Id })" class="btn btn-success btn-fw" data-style="expand-right">
                                                <span class="ladda-label">
                                                    <i class="fa fa-pencil-square-o"></i>
                                                </span>
                                            </a>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

Table Structure: The table includes columns for various attributes of the democurd records and an action column for editing.
Add Button: A button to add a new record, redirecting to the StationMasterAddEdi action.

JavaScript for DataTable and Alerts

JavaScript code to initialize DataTable and display success or failure alerts.

@section scripts {
    @{
        if (TempData["AlertError"] != null)
        {
            <script>
                swal("Failure", "@TempData["AlertError"].ToString()", "error");
            </script>
        }
        if (TempData["AlertSuccess"] != null)
        {
            <script>
                swal("Success", "@TempData["AlertSuccess"].ToString()", "success");
            </script>
        }
    }
}


<script>
    $(document).ready(function () {
        window.showLoading({ name: 'jump-pulse', allowHide: true });
        $('#dataTableModules1').dataTable({
            autoWidth: false,
            responsive: true,
            "bLengthChange": true,
            "bFilter": true,
            "language": {
                "searchPlaceholder": "Search"
            },
            "aaSorting": [],
            "sPaginationType": "full_numbers",
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'copyHtml5',
                    text: '<i class="fa fa-files-o"></i> Copy',
                    titleAttr: 'Copy'
                },
                {
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i> Excel',
                    titleAttr: 'Excel'
                },
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-text-o"></i> CSV',
                    titleAttr: 'CSV'
                },
                {
                    extend: 'pdfHtml5',
                    text: '<i class="fa fa-file-pdf-o"></i> PDF',
                    titleAttr: 'PDF'
                }
            ]
        });
        setTimeout(function () {
            window.hideLoading();
        }, 1000);
    });
</script>

  • Alerts: Displays success or failure alerts based on TempData values.
  • DataTable Initialization: Initializes the DataTable with specific options and buttons for exporting data.

Form for Adding or Editing democurd Records
A form for adding or editing democurd records with validation and anti-forgery protection.
@using (Html.BeginForm("democurdAddEdi", "democontroller", FormMethod.Post, new { id = "__AjaxAntiForgeryForm", role = "form", LoadingElementId = "please-wait" }))
{
    @Html.AntiForgeryToken()
    <div class="form-body">
        <div class="row">
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">Station Name<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.Name, new { placeholder = "Enforcement Name", @class = "form-control", onkeypress = "return onlyAlphabets(this, event);", maxlength = "100", @required = true })
                        @Html.HiddenFor(m => m.StationId)
                        <span class="help-block">@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">Mobile Number<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.Number, new { placeholder = "Number", @class = "form-control", onkeypress = "return onlyNumber(this, event);", maxlength = "10", minlength = "10", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.Number, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">val<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.val, new { placeholder = "val", @class = "form-control", onkeypress = "return onlyNumberwithDot(this, event);", maxlength = "100", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.val, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">valtude<span class="text-danger">*</span></label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.valtude, new { placeholder = "valtude", @class = "form-control", onkeypress = "return onlyNumberwithDot(this, event);", maxlength = "100", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.valtude, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-3">
                <div class="form-group form-md-line-input form-md-floating-label">
                    <label for="form_control_1">status</label>
                    <div class="input-icon right">
                        @Html.TextBoxFor(m => m.status, new { placeholder = "status", @class = "form-control", @required = true })
                        <span class="help-block">@Html.ValidationMessageFor(m => m.status, "", new { @class = "text-danger", style = "white-space:nowrap" })</span>
                    </div>
                </div>
            </div>
            <div class="form-actions noborder pull-right">
                <a href="@Url.Action("methodname", "controllername")" class="btn btn-danger btn-flat"><i class="fa fa-ban fa-fw"></i>Cancel</a>
                <button id="btnSubmit" type="submit" class="btn btn-info btn-flat"><i class="fa fa-save fa-fw"></i>Submit</button>
            </div>
        </div>
    </div>
}


Conclusion
In this article, we've covered the implementation of CRUD operations in an ASP.NET MVC application using Razor views and C#. We explored the various controller actions responsible for listing, adding, and editing records. Additionally, we discussed the Razor views for displaying the records in a table and providing forms for user input.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Performance Optimization in ASP.NET MVC Applications

clock June 27, 2024 08:03 by author Peter

Performance optimization for ASP.NET MVC (Model-View-Controller) applications use a range of techniques in an effort to improve the efficiency, responsiveness, and speed of applications created using this framework. The following are some key areas and methods for optimizing the performance of ASP.NET MVC applications.

1. Efficient data access
Use Entity Framework wisely: Optimize queries, use lazy loading carefully, and prefer compiled queries for frequently used data access paths.
Stored Procedures: Use stored procedures for complex and frequently run queries to reduce the overhead of query parsing and execution planning.
Caching: Implement caching strategies like output caching, data caching, and distributed caching (e.g., using Redis) to reduce database load.

2. Optimizing server-side code
Async/Await: Use asynchronous programming (async/await) to handle I/O-bound operations without blocking threads.
Minimize ViewState: Reduce the use of ViewState to decrease the payload size.
Bundling and Minification: Combine and minify CSS and JavaScript files to reduce the number of HTTP requests and the size of requested resources.
Compression: Enable GZIP compression in IIS to compress the response data sent to the client, reducing the response size.

3. Efficient use of resources
Pooled Connections: Use connection pooling to reuse database connections.
Memory Management: Properly manage memory usage to avoid excessive garbage collection and memory leaks.
Thread Pooling: Utilize thread pooling to manage a pool of worker threads, which can be reused for executing tasks, reducing the overhead of thread creation.

4. Front-end performance
Lazy Loading: Implement lazy loading for images and other resources to load them only when they are in the viewport.
Content Delivery Network (CDN): Use CDNs to serve static resources like images, CSS, and JavaScript files from locations closer to the user, reducing latency.
Browser Caching: Set appropriate caching headers to enable browsers to cache static resources.

5. Optimizing Queries and Data Access
Indexing: Properly index database tables to improve query performance.
Pagination: Implement pagination for data-heavy views to load only a subset of data at a time.
Query Optimization: Analyze and optimize LINQ queries to reduce execution time.

6. Application Monitoring and Profiling
Application Insights: Use tools like Azure Application Insights for monitoring and diagnostics to identify performance bottlenecks.
Profiling Tools: Use profiling tools to analyze the performance of your application and identify hotspots.

7. Configuration and Deployment

Configuration Settings: Tune application settings such as session state management, request timeouts, and garbage collection modes.
Scalability: Design the application to be scalable, allowing it to handle increased load by adding more resources (horizontal scaling) or optimizing resource usage (vertical scaling).

8. Load Balancing
Load Balancers: Use load balancers to distribute incoming traffic across multiple servers, ensuring no single server is overwhelmed.
Session State Management: Ensure the session state is managed in a distributed manner (e.g., using a distributed cache) to support load balancing.

Example implementation
Here’s an example of how to implement output caching in an ASP.NET MVC controller.

using System.Web.Mvc;
public class HomeController : Controller
{
    [OutputCache(Duration = 60, VaryByParam = "none")]
    public ActionResult Index()
    {
        return View();
    }
}

In this example, the OutputCache attribute is applied to the Index action method, caching the output for 60 seconds.

Conclusion

By implementing these strategies, you can significantly improve the performance of your ASP.NET MVC application. Each application is unique, so it's important to profile and monitor your specific application to identify the most effective optimization techniques.



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