European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.NET MVC Architecture Core: Comprehensive Synopsis

clock March 10, 2026 08:55 by author Peter

A popular architectural style used in ASP.NET Core to create organized, scalable, and maintainable online applications is called MVC (Model–View–Controller). It guarantees a clear division of concerns by dividing an application into three primary parts.

MVC is particularly effective for enterprise-level systems where scalability, testability, and organization are crucial.

What is MVC?

  • MVC is a design pattern that divides an application into:
  • Model – Handles data and business logic
  • View – Handles user interface
  • Controller – Handles request processing and coordination
  • This separation ensures that each component has a single responsibility.

Core Components in Detail
1. Model

The Model represents the data and business rules of the application.

It is responsible for:

  • Managing application data
  • Interacting with the database
  • Applying business logic
  • Performing validations
  • Enforcing rules
  • The model does not depend on UI elements. It focuses only on data and logic.

In large applications, models often work with data access layers or ORM tools to communicate with databases.

2. View
The View is responsible for displaying data to users.

It:

  • Renders UI (HTML content)
  • Displays data provided by the controller
  • Contains minimal logic (mostly presentation logic)
  • In ASP.NET Core, views typically use Razor syntax to dynamically generate content.
  • Views should never contain business logic. Their sole responsibility is presentation.

3. Controller
The Controller acts as the bridge between the Model and View. It is responsible for:

  • Handling incoming HTTP requests
  • Processing user input
  • Calling the Model to retrieve or update data
  • Selecting and returning the appropriate View
  • Controllers manage the application flow and coordinate responses.

How MVC Works – Request Lifecycle

  1. A user sends a request through a browser.
  2. The request is routed to a specific controller.
  3. The controller processes the request.
  4. The controller interacts with the model if data is required.
  5. The controller passes data to the view.
  6. The view renders the final output.
  7. The response is sent back to the user.
  8. This structured flow improves clarity and maintainability.

Key Features of MVC in ASP.NET Core
Routing
Maps incoming URLs to specific controller actions.

Model Binding

Automatically maps HTTP request data to application models.

Validation
Supports data validation using built-in mechanisms.

Filters

Allows execution of logic before or after controller actions (e.g., authentication, logging).

Dependency Injection
Built-in support for injecting services into controllers.
Advantages of MVC Architecture

1. Separation of Concerns

Each component has a specific role, making the application easier to manage.

2. Testability

Controllers and models can be unit tested independently.

3. Scalability

Applications can grow without becoming unstructured.

4. Maintainability
Changes in UI do not affect business logic and vice versa.

5. Team Collaboration

Developers, designers, and database engineers can work independently on different layers.

MVC vs Traditional Web Forms

Compared to older approaches:

  • MVC provides more control over HTML output.
  • It promotes cleaner architecture.
  • It follows RESTful design principles.
  • It is more suitable for modern web applications.

When to Use MVC
MVC is ideal for:

  • Enterprise applications
  • Data-driven websites
  • Applications requiring clear separation of logic
  • Projects with multiple developers
  • Scalable and maintainable web solutions

Conclusion
A strong and organized method for creating web apps in ASP.NET Core is the MVC architecture. It guarantees clear design, enhanced testability, and long-term maintainability by keeping data, UI, and control logic apart. To create professional, enterprise-grade online apps, any serious ASP.NET Core developer must grasp MVC architecture.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Recognizing MVC's Fundamentals

clock March 5, 2026 09:30 by author Peter

Add the below code in a View and run the application.We will go over the fundamentals of MVC in this post. The concepts of MVC and examples of one Controller, one Model, and one View or several were found in the majority of the MVC articles. We'll talk about the prerequisites for implementing an MVC application here. Are Controller, Model, and View all required? Is it possible to create an MVC application with just a model, controller, etc.? This will enable us to comprehend the true connection between these three MVC components.

We'll talk about this while writing the code for a brief real-time issue statement. After we've finished writing all of the code, we'll also rapidly grasp the theory. Indeed, the hypothesis will be presented at the conclusion.

We will use an empty MVC web application that Visual Studio provides to demonstrate the code base, and we will add the necessary code.

Statement of the Problem
Now, let's look at a very basic example (but the topic is applicable to all MVC apps, regardless of size). Let's say we have a requirement that requires us to either construct an MVC ContactUs page or add this page to an already-created MVC application.

Now consider: Do we require a controller? Yes, is the response. An HTTP request will be sent to the application via the controller. Thus, we are unable to prevent that. We realize that in order to build an MVC application, controllers are always required. For the time being, put the Model and View on hold and begin working on the Controller. We will talk about them in a similar manner.

Launch an MVC application by following the instructions below:

Click OK after choosing "Empty" as the template and "MVC" in the folder references. No other options need to be changed. This will provide you with a pre-made MVC folder structure without a Controller, Model, or View. We shall make those from the ground up.

Understanding the Controller
We have already discussed that Controller is essential. But, is a Controller alone is enough to create a MVC application? Again, the answer is, YES, at least in some scenarios. 
Now suppose, you get a requirement twist; the company is getting their addresses changed and for now, we just need to display “Page is under construction” on ContactUs page.
Let’s achieve this through only a Controller. Create a Controller class ContactUsController.cs in Controllers folder, as shown below: 

Add the following code in this file.


Run the application and see what we get. We get the following screen.

We can even return the HTML with a little code change. Use the below code instead and browse the page. Return Content("<h1>Page is under construction</h1>", "text/html"); 
We will now get this screen. 

So far, we learned that the Model and the Views are not necessary to create an MVC application. A Controller can be enough in some scenarios, as discussed above. Now, let’s bring the View into the picture.

Understanding the View
View can also be used with or without Model. Let’s first use View with no Model associated with that and later, we will discuss about Model.

Now, let’s say, you get another update in requirements that for now we need to show only one office detail. So, we need to show only one address, city, country,  and contact number on contact us page as a table. As we need to add a table and some other styling, let’s use a View to achieve this. And, because we just have one static data, we can easily add that in the View itself with no Model.

Inside Views/ContactUs folder, add Index.cshtml, as shown below:

Add the below code in a View and run the application.

In the above code, we just created a table and fixed the data in View itself (because it’s a single fix data). Also, in earlier code, we return a small HTML from our Controller itself. Let’s change that code to the following:

When we run the application.

Understanding the Model
Now that we are done with Controller and View, let’s discuss the limitations with not having a Model. Imagine, there is another addition in the requirement which says that we need to show all the addresses (3 as of now) of our offices, and the company will add a new address every month. In this situation, we have to have a database where addresses will keep on adding and we have to show all these addresses in our View dynamically. This is substantial work if done in a View. Let’s bring a Model in the code to make it easier and more dynamic.

Add a modal class “Contacts.cs” in Models folder. 

Add the below code in this class.

In our Model, we have 4 properties (City, Country, Address and ContactNo) which our complete office address contains. Notice, we are using a Contacts.json file as a data source here. In reality, it can be a database, a service, or a file itself whatever suits the project.

Inside GetContacts function, we are just fetching the address detail from JSON file, creating a list of Contacts, and returning a very simple modal class, fetching the data from a flat file and returning the same.

To add a JSON file, add a file “Contacts.json” in Appdata folder and add some data in to it. Now, our Model is also created. Let’s use it with some minor changes in our Controller and View. Update code as the below one and run the application.

Inside View, first add Model reference, as given below:

Now, comment the static data present inside the View and add the logic to show the data from the Model, as shown below: 

Also we needed a minor change in Controller. We need to populate the Model with data using the function we just created inside model class. And then, pass this model object to the View, so that the View can use it and show the dynamic data on screen. This is simple. Just make the following changes in Controller class:

Now, run the application again. We will get the same screen but now with dynamic data.

Just add more data in JSON file and refresh the page. All the data from the JSON  should be visible on screen with no code change. As an exercise, you can now try to add some more data in the JSON, add some more properties to the contact us, and do some more styling to make it better.

Summary
Now that we have seen all the code, here are few theory points we learned:

  • Controller is essential. This is a must in an MVC application. Don’t avoid that..:)
  • Controller is responsible for returning the View to the caller and if “How” part of the data is small or insignificant, it can take “How” responsibility as well.
  • View is responsible for “How” to show the data. But if “What” part of the data is small or insignificant, it can take “What” responsibility as well.
  • Model is responsible for “What” part of the data. It's Model’s responsibility to get or create the data. It can fetch the data from any data source, manipulate it if required, and return that to the Controller. Controller then passes that to the View, so that the View can use that. 


ASP.NET MVC Hosting - HostForLIFEASP.NET :: How Can an ASP.NET MVC Project Make Use of AI Agents?

clock February 27, 2026 07:25 by author Peter

Using contemporary APIs (OpenAI, Azure OpenAI, Hugging Face, and self-hosted LLMs), this article describes how to include AI agents into ASP.NET MVC.

What Is an AI Agent?
An AI Agent is an autonomous component capable of:

  • Understanding user input
  • Taking decisions
  • Calling tools (APIs, DB, services)
  • Updating its memory
  • Producing actions or responses
  • Triggering workflows

In an MVC project, an AI Agent often acts as:

  • Chatbot
  • Automated email writer
  • Code generator
  • Ticket classification bot
  • Data extraction worker
  • Knowledge base assistant

Project Structure (MVC)
Your MVC app will use:
Controllers/
    AiAgentController.cs
Services/
    AiAgentService.cs
Models/
    AiRequest.cs
    AiResponse.cs
Views/
    AiAgent/
        Index.cshtml


Step 1: Install Required Nuget Packages
For OpenAI-compatible agents:
Install-Package OpenAI
Install-Package Newtonsoft.Json


OR for Azure OpenAI:
Install-Package Azure.AI.OpenAI

Step 2: Create Your AI Agent Service (Backend Logic)
Create: Services/AiAgentService.cs
using OpenAI.Chat;
using OpenAI;
using System.Threading.Tasks;

namespace YourApp.Services
{
    public class AiAgentService
    {
        private readonly OpenAIClient _client;

        public AiAgentService(string apiKey)
        {
            _client = new OpenAIClient(apiKey);
        }

        public async Task<string> AskAgentAsync(string userInput)
        {
            var chat = _client.GetChatClient("gpt-4o-mini");

            var response = await chat.CompleteAsync(
                userInput
            );

            return response.Content[0].Text;
        }
    }
}


Step 3: Add the Service to Dependency Injection
Open Global.asax.cs (or Program.cs for .NET 6+ MVC)

For .NET 4.8 MVC
In UnityConfig.cs or Autofac:
container.RegisterType<AiAgentService>(
    new InjectionConstructor("YOUR_OPENAI_API_KEY")
);

For .NET 6/7 MVC
Program.cs
builder.Services.AddSingleton<AiAgentService>(new AiAgentService("YOUR_API_KEY"));

Step 4: Create Controller to Call the AI Agent

Controllers/AiAgentController.cs
using System.Threading.Tasks;
using System.Web.Mvc;
using YourApp.Services;

namespace YourApp.Controllers
{
    public class AiAgentController : Controller
    {
        private readonly AiAgentService _ai;

        public AiAgentController(AiAgentService ai)
        {
            _ai = ai;
        }

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

        [HttpPost]
        public async Task<ActionResult> Index(string userMessage)
        {
            var aiResponse = await _ai.AskAgentAsync(userMessage);
            ViewBag.Response = aiResponse;
            return View();
        }
    }
}


Step 5: Create Razor View for Chat UI
Views/AiAgent/Index.cshtml
@{
    ViewBag.Title = "AI Agent Chat";
}

<h2>AI Agent in MVC</h2>

<form method="post">
    <textarea name="userMessage" class="form-control" rows="4" placeholder="Ask anything..."></textarea>
    <br />
    <button class="btn btn-primary">Send</button>
</form>

@if (ViewBag.Response != null)
{
    <div class="alert alert-info" style="margin-top:20px;">
        <strong>AI Agent Reply:</strong>
        <p>@ViewBag.Response</p>
    </div>
}

Your First AI Agent Is Ready
You can now run:
/AiAgent/Index

Type a message:
“Summarize this text”
“Generate email template for refund request”
“Write C# code for a stored procedure call”
“Fix my SQL query”


The agent instantly responds.

Advanced: Add Tools (Function Calling)

Agents become powerful when they can call functions inside your MVC app.

Example: Agent gets order status from your database.

Step 1: Add a Tool Method

public string GetOrderStatus(int orderId)
{
    return "Order " + orderId + " is in Packaging Stage.";
}


Step 2: Expose Tool to Agent
Most AI SDKs support function-calling like:
var response = await chat.CompleteAsync(
    messages: userInput,
    functions: new[]
    {
        new FunctionDefinition(
            "get_order_status",
            "Get order status using order ID",
            new { orderId = "number" }
        )
    });


Result:
Agent decides to call your function → Your C# method runs → Response returned back.
Real-World AI Agent Use Cases in MVC
1. Customer Support Assistant


Automatically understands user message → replies or creates ticket.

2. Form Auto-Generation
User describes what form they need → agent builds HTML form dynamically.

3. Code Generator Inside Admin Panel
Generate C# classes, views, DB queries on the fly.

4. Workflow Automation

User enters command → agent runs server-side tasks.

5. Knowledge Base Search Agent
AI agent + vector database → semantic search.

Advanced: Adding Memory to AI Agent

Short-term memory → history stored in session
Long-term memory → store in DB or vector DB (like Qdrant, Pinecone)

Session["history"] += userMessage + aiResponse;


Performance Tips & Best Practices
✔ Cache frequently used prompts

Use IMemoryCache or Redis.
✔ Avoid sending huge previous chat

Compress or summarize conversation.
✔ Always use streaming for faster response

Most SDKs support streaming tokens.
✔ Background agents for heavy tasks

Use Windows Service.

Common Mistakes Developers Make

MistakeWhy BadFix

Sending full chat on each request

slow, expensive

send only last 5 turns

No rate limiting

can exhaust API credits

use retry policy

Hardcoding API keys

big security risk

use environment variables

Not handling null/empty response

crashes

always validate

Using wrong model (too large)

expensive

use small model for simple tasks

Final Thoughts

AI Agents will become a core part of all ASP.NET MVC applications.
With just a few steps, you can:

  • Add smart chatbots
  • Automate workflows
  • Enhance admin panels
  • Add dynamic intelligence
  • Build modern AI-driven enterprise apps


ASP.NET MVC Hosting - HostForLIFEASP.NET :: ASP.NET MVC Filters: A Comprehensive Guide with Examples

clock February 4, 2026 08:48 by author Peter

ASP.NET MVC offers filters to run custom logic either prior to or following particular request processing phases. Without having to write repetitious code inside controllers, filters assist developers in managing cross-cutting issues like authentication, authorization, logging, and exception handling.

In this article, we will learn:

What filters are in ASP.NET MVC

  • Types of filters
  • Execution order of filters
  • How to create custom filters
  • Real-world use cases

What Are Filters in ASP.NET MVC?
Filters are attributes that can be applied to:

  • Controllers
  • Action methods
  • Entire application (global filters)

They allow developers to run logic before or after an action method executes.

Why Use Filters?

  • Code reusability
  • Separation of concerns
  • Cleaner controllers
  • Centralized logic

ASP.NET MVC Request Life Cycle
Understanding where filters fit in the MVC pipeline is important.

MVC Request Flow:

  • Request received
  • Routing
  • Controller initialization
  • Filters execution
  • Action method execution
  • Result execution
  • Response returned

Filters act as checkpoints during this lifecycle.

Types of Filters in ASP.NET MVC

ASP.NET MVC provides the following types of filters:

  • Authorization Filters
  • Action Filters
  • Result Filters
  • Exception Filters
  • Authentication Filters (MVC 5)

1. Authorization Filters
Authorization filters are used to check whether a user is authorized to access a resource.

Built-in Authorize Attribute

[Authorize]
public ActionResult Dashboard()
{
    return View();
}

This allows only authenticated users to access the action.

Custom Authorization Filter

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return httpContext.User.Identity.IsAuthenticated;
    }
}


Usage:
[CustomAuthorize]
public ActionResult Profile()
{
    return View();
}

2. Action Filters
Action filters execute logic before and after an action method.
Action Filter Methods

  • OnActionExecuting
  • OnActionExecuted

Example: Custom Action Filter
public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Debug.WriteLine("Action Method Executing");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Debug.WriteLine("Action Method Executed");
    }
}


Usage:
[LogActionFilter]
public ActionResult Index()
{
    return View();
}


3. Result Filters
Result filters execute before and after the action result (such as ViewResult).
Result Filter Methods

  • OnResultExecuting
  • OnResultExecuted


Example
public class ResultFilter : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Debug.WriteLine("Result Executing");
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Debug.WriteLine("Result Executed");
    }
}

4. Exception Filters
Exception filters handle unhandled exceptions that occur during action execution.
Example: Custom Exception Filter
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new ViewResult
        {
            ViewName = "Error"
        };
    }
}


Register Exception Filter Globally
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new CustomExceptionFilter());
}


5. Authentication Filters (ASP.NET MVC 5)
Authentication filters run before authorization filters and are used to verify user identity.
public class CustomAuthenticationFilter : IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        // Authentication logic
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        // Challenge logic
    }
}


Filter Scope Levels
Filters can be applied at different levels:

  • Global Level – Applies to entire application
  • Controller Level – Applies to specific controller
  • Action Level – Applies to specific action

Global Filter Registration Example
filters.Add(new LogActionFilter());

Order of Execution of Filters
The execution order of filters is:

  • Authentication Filters
  • Authorization Filters
  • Action Filters
  • Result Filters
  • Exception Filters

Understanding this order helps prevent unexpected behavior.

Advantages of Using Filters

  • Promotes clean architecture
  • Reduces duplicate code
  • Improves maintainability
  • Centralized handling of common logic
  • Enhances application performance

Real-World Use Case
Scenario: Logging user activity across the application.

Solution:
Create a global action filter to log:

  • Controller name
  • Action name
  • Request time

This avoids writing logging logic in every controller.

Best Practices

  • Keep filters lightweight
  • Avoid business logic inside filters
  • Use global filters wisely
  • Handle exceptions centrally
  • Use attributes only where required

Conclusion
Filters in ASP.NET MVC play a vital role in building clean, scalable, and maintainable applications. They help manage cross-cutting concerns efficiently and reduce repetitive code. Understanding filter types, execution order, and scope will help developers write better MVC applications.

Mastering filters is essential for any ASP.NET MVC developer.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: HTTP Error 404.0 0 Not Found in MVC

clock January 21, 2026 08:55 by author Peter

The resource you are searching for is either temporarily unavailable, has been removed, or has had its name changed.

While working on an MVC web project today, I noticed this problem, which is frequently seen when operating websites and carrying out any CRUD (Create, Read, Update, Delete) activity. I choose to explain the solution here because there are a lot of these questions in the Stackoverflow forum. I believe most requests can be fulfilled, albeit you might not find it helpful in your situation.

I'll show you a picture of an error page:

Look at the URL in the above image. The URL is requesting a view/page to edit the record but unfortunately the page is not found. Actually the page/view is already there but the problem is, we are not supplying the correct ID or say index to edit. In other words we need an URL something like http://localhost:25349/demo/Edit/1 to edit the first record and http://localhost:25349/demo/Edit/2 to edit the second record. Yet in the preceding image we are not supplying the ID.
 
Let's fix it. Open the "Index" view of the "demo" controller and look at the existing code:

Oh! there is a comment instead of the ID parameter, so once you change it, such as in the following: 
    <td>  
        @Html.ActionLink("Edit", "Edit", new { id=item.SM_UID }) |  
        @Html.ActionLink("Details", "Details", new { id=item.SM_UID }) |  
        @Html.ActionLink("Delete", "Delete", new { id=item.SM_UID })  
    </td>  


Your application will work fine.
I hope this fix will help you.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: In MVC, Handle View Without Controller Action

clock January 8, 2026 08:34 by author Peter

Why is this necessary?
Let's examine the picture that follows.

You can see that there is a corresponding controller action for every view in the image above. There is only one line of code in each of these activities. In actuality, the exact same line of code appears in each of these activities. Furthermore, this is totally superfluous. When you receive hundreds or thousands of views, just think of what you will do. Will you produce thousands or hundreds of controller actions? Of certainly not, but how can we make it right?



When we try to launch an action on a controller that doesn't exist (or when we request a view that doesn't have a corresponding action method), the MVC Framework's controller class contains a method called HandleUnknownAction().

Now we are taking advantage of the HandleUnknownAction() method to render views even when a corresponding controller method does not exist. In the image above you can see we don't have Post5.cshtml, so when I tried to access the Post5.cshtml view, it shows the following error.

Here's how to utilize a straightforward try-catch block to fix this problem and reroute the user to a PageNotFound view.




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Real-Time SignalR Message Conversation App Using ASP.NET MVC 5

clock October 22, 2025 09:53 by author Peter

SignalR is an open library which can be used to integrate in real time in your applications. There are some areas where SignalR can come in handy to make your application integrated, and more responsive to the end user. Your server responds very quickly to the client when a request is made.

Description
SignalR gives two directional communication between server and client. SignalR can be used in faster notification message to the end user and in another sense if any problem exists in the server side then it can be notified by using signalR concept.

SignalR can be used in file uploading , file downloading and how much percentage it has completed, and how much time it will take. So, in these fields we can implement signalR concept for better results.

In more cases signalR is used for Chat application purposes and in the integration of Facebook, Google Plus etc.

Most Used Fields
SignalR can be used to show the result of current actions made in server controls.

For example
In webgrid of Asp.Net MVC when we perform Crud operations the signalR shows the task the record using the Id entered , updated or deleted.

It just shows like system task manager.

There are two sides -- One is Server Side and another one is Client Side. The Hub in server side invokes the client side function from Hub Proxy.
Here a response is made.

Here The Hub Proxy in Client Side invokes the server side function from Hub.

Here Request Is Made.

signalR can be hosted using Open Web Interface in .NET called OWIN in signalR In another sense it can be self-hosted. It has the ability to send the contents of a server to currently connected clients.

Remote Procedure Calls (RPC)
SignalR provides an API which helps in making the call between the server and the client. The server calls the functions on the client side and the client side calls the server side. That somehow is called "Server-Push".

SignalR Transport Medium
It is integrated with ASP.NET web applications, it can be implemented by other .NET Client side Application like Windows Phone or even Windows 8/10 application.

It has four transport mediums like

  • WebSocket.
  • Server-Sent Event.
  • ForEver Frame.
  • Long Polling.

Notes
SignalR initiates with HTTP and then upgrades to a WebSocket if the connection is available. An advantage of WebSocket is it can be used by both client and server applications. SignalR supports the transport based on the browser; i.e. which required transport the browser supports. Server Sent events are also called Event Source, which is not supported by only IE browser.
Create A SignalR Chat Based Application using MVC

Step 1
I have created one Asp.net mvc application using .Net Framework 4.5 and Visual Studio 2013 Edition.

Then The MVC 5 signalR application is created and named “MVCsignalR”

You can Check mvc version Here in Second right side Pic.

Step 2

Then add signalR Related DLL reference files from NuGet Package Manager.

After installation of these three files from NuGet Package manager you can check these signalR DLL files. You can check also Open Web Interface in .NET called  “OWIN” related DLL files which are responsible for sending the contents of a server to currently connected clients.

Also you can check signalR related javascript files which already have been added.

The version of signalR Javascript files are the same as signalR DLL files.

See as mentioned below.

Step 3
Then I created one OWIN Startup class named “Startup.cs”.
Image Ref,

Code ref 
    using Microsoft.Owin;    
    using Owin;    
        
    [assembly: OwinStartupAttribute(typeof(MVCsignalR.Startup))]    
    namespace MVCsignalR    
    {    
        public partial class Startup    
        {    
            public void Configuration(IAppBuilder app)    
            {    
                app.MapSignalR();    
            }    
        }    
    } 


Code Description
To Enable signalR in the project we have to add StartUp Class.

OWIN Application has a startup class where you mention components for the application pipeline. There are various ways you can connect your startup class with the runtime, depending on the hosting models like (OwinHost, IIS, and IIS-Express).

OwinStartup Attribute is the most general class that is used by the developers to determine the Startup class.
    [assembly: OwinStartupAttribute(typeof(MVCsignalR.Startup))]   

Any connection or hub wire up and configuration should go here to this line of StartUp classes.
    app.MapSignalR();  

If you want to know all package related information including version and tergetFramework then go to packages.config file.

Step 4
Then add a controller named “HomeController.cs”.

Code Ref 
    using System;    
    using System.Collections.Generic;    
    using System.Linq;    
    using System.Web;    
    using System.Web.Mvc;    
    namespace MVCsignalR.Controllers    
    {    
        public class HomeController : Controller    
        {           
            public ActionResult Chat()    
            {    
                return View();    
            }   
        }  
    } 

Code Description
Here I defined a controller action result method called Chat().

Step 5
In Solution Explorer, right-click the project, select Add > New Folder, and add a new folder named Hubs. Right-click the Hubs folder, click Add > New Item, select SignalR Hub Class (v2) from the center pane, and create a new hub named ChatHub.cs.

This class is used as a SignalR server hub that sends messages to all clients. You will use this class as a SignalR server hub that sends messages to all clients.

Code Ref
    using System;    
    using System.Collections.Generic;    
    using System.Linq;    
    using System.Web;    
    using Microsoft.AspNet.SignalR;    
        
    namespace MVCsignalR.Hubs    
    {    
        public class ChatHub : Hub    
        {    
            public void Send(string name, string message)    
            {    
                Clients.All.addNewMessageToPage(name, message);    
            }    
        }    
    } 

Code Description
Here I added one namespace to access methods for response to client requests.
    using Microsoft.AspNet.SignalR;   

ChatHub class is derived from Hub base class.

Hub base class provides methods that communicates with signalR connections that are connected to this Hub base class.
    public class ChatHub : Hub   


Here I defined a method called Send access two parameter values to take User Name and User Message and Show this User Name and User Message to other users and Vice Versa.
    public void Send(string name, string message)  
    {  
        Clients.All.addNewMessageToPage(name, message);  
    }  

SignalR chat application demonstrates two basic SignalR development things: Develop a hub as the main coordination object on the server, and using the SignalR jQuery library to send and receive messages.

You create public methods on your hub class and then access those methods by calling them from javascripts in a web page.

Clients call the method to send a new message.

ChatHub.Send

The hub in turn sends the name and message to all clients by calling.

Clients.All.addNewMessageToPage

Call a function on the client to update the clients.

Clients.All.addNewMessageToPage(name, message);


Use this property to access all clients connected to this hub.

Microsoft.AspNet.SignalR.Hub.Clients

This Send method of this ChatHub.cs class from the client with the parameters after the connection is fixed on the client side. Once the server receives that request from the client, it processes and sends that response to the client, using appendNewMessage. This appendNewMessage method is set on the client side to receive the response from server side and display it in the User Interface to the client side. 

    public void Send(string name, string message)  
    {  
        Clients.All.addNewMessageToPage(name, message);  
    }  


Step 6
Then I have added a view named “Chat.cshtml” of Home Controller class.

Code Ref 
    @{  
        ViewBag.Title = "Chat";  
    }  
    <fieldset>  
        <legend style="color:orangered">Welcome To  peter's signalR MVC Group Chat Club</legend>  
    </fieldset>  
    <div class="form-group col-xl-12">  
        <label style="color: blue; font-style: oblique;font-size: medium" id="label1">Write Your Message Here!</label><br />  
        <textarea class="form-control" rows="4" cols="40" id="message" placeholder="Share what's in your mind..."></textarea>  
        <br />  
        <input type="button" class="btn btn-primary" id="sendmessage" value="Send" />  
        <br />  
        <br />  
        <label style="color: blue;font-style:oblique;font-size:medium" id="label2">Group Chat Conversations History</label>  
        <div class="container chatArea">  
            <input type="hidden" id="displayname" />  
            <ul id="discussion"></ul>  
        </div>  
    </div>  
    @section scripts {  
        <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>  
        <script src="~/signalr/hubs"></script>  
        <script>  
            $(function () {  
                var chat = $.connection.chatHub;  
                chat.client.addNewMessageToPage = function (name, message) {  
                    $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'  
                        + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  
                };  
                $('#displayname').val(prompt('Your Good Name Please:', ''));  
                $('#message').focus();  
                $.connection.hub.start().done(function () {  
                    $('#sendmessage').click(function () {  
                        chat.server.send($('#displayname').val(), $('#message').val());  
                        $('#message').val('').focus();  
                    });  
                });  
            });  
            function htmlEncode(value) {  
                var encodedValue = $('<div />').text(value).html();  
                return encodedValue;  
            }  
        </script>  
    }   


Code Description
    @{  
        ViewBag.Title = "Chat";  
    } 
 

This above part where I added some title text in the browser title bar with addition of title text of “_Layout.cshtml”.
    <fieldset>  
        <legend style="color:orangered">Welcome To  peter's signalR MVC Group Chat Club</legend>  
    </fieldset>   


This above part is where I added some headline text of this chat application in signalR.
    <label style="color: blue; font-style: oblique;font-size: medium" id="label1">Write Your Message Here!</label>   

This above part is where I added one label control for message box.
    <textarea class="form-control" rows="4" cols="40" id="message" placeholder="Share what's in your mind..."></textarea>   

This above part is where I added multiline text box to let user enter messages.
    <input type="button" class="btn btn-primary" id="sendmessage" value="Send" />   


This above part is where I added one button control to send messages to other users after putting some messages in the multiline textbox.
    <label style="color: blue;font-style:oblique;font-size:medium" id="label2">Group Chat Conversations History</label>   

In the above part I added one label control for chat history area that means whatever messages are received and sent between receiver and sender. 
    <div class="container chatArea">  
            <input type="hidden" id="displayname" />  
            <ul id="discussion"></ul>  
    </div>   


This above part is where I added one chat area box that will show whatever  messages are received and sent between receiver and sender.

Then two ids,  one “displayname” and “discussion,” will show the receiver and sender names along with their conversations in the current forum session in the chat history area box. 
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>  
    <script src="~/signalr/hubs"></script>   

This above part is where I added script file references to access some signalR based scripting functionalities and show to the end user.
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>   

Script references. The jQuery library is required and is referenced by default in _Layout.cshtml Reference the SignalR library.
    <script src="~/signalr/hubs"></script>   

Reference the autogenerated SignalR hub script. 

    <script>  
            $(function () {  
                var chat = $.connection.chatHub;  
                chat.client.addNewMessageToPage = function (name, message) {  
                    $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>'  
                        + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  
                };  
                $('#displayname').val(prompt('Your Good Name Please:', ''));  
                $('#message').focus();  
                $.connection.hub.start().done(function () {  
                    $('#sendmessage').click(function () {  
                        chat.server.send($('#displayname').val(), $('#message').val());  
                        $('#message').val('').focus();  
                    });  
                });  
            });  
            function htmlEncode(value) {  
                var encodedValue = $('<div />').text(value).html();  
                return encodedValue;  
            }  
        </script>   


This is the SignalR script to update the chat page and send messages.

The Chat.cshtml shows how to use the SignalR jQuery library to contact with a SignalR hub. The codes are creating a reference to the Self-generated proxy for the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hubs.

It is a reference to a hub proxy.
    var chat = $.connection.chatHub;

It references the auto-generated proxy for the hub.

Here “chatHub” is the Hub class to make connection related functionalities.

This shows howt to create a callback function in the script. The hub class on the server calls the function to push content updates to each client. The optional call to the htmlEncode function shows a path to HTML to encode the message content before displaying it in the page. As a result way it will prevent script injection.
    chat.client.addNewMessageToPage = function (name, message)

It creates a function that the hub can call back to display messages.Here the addNewMessageToPage method to update clients as defined in ChatHub class.
    $('#discussion').append('<ul style="list-style-type:square"><li><strong style="color:red;font-style:normal;font-size:medium;text-transform:uppercase">' + htmlEncode(name) + '  ' + '<strong style="color:black;font-style:normal;font-size:medium;text-transform:lowercase">said</strong>' + '</strong>: ' + '<strong style="color:blue;font-style:oblique;font-size:medium">' + htmlEncode(message) + '</strong>' + '</li></ul>');  

Add the message to the chat area box.

This above mentioned code will show the name and messages of the users in chat area textbox by taking two parameter values defined in addNewMessageToPage method.
    $('#displayname').val(prompt('Your Good Name Please:', ''));   

Get the user name and store it to prepend to messages.

This part will ask your to mention your user name to process your valid message conversation part.
    $('#message').focus();   


It sets initial focus to message input box.
    $.connection.hub.start().done(function () {   


Here I added code to Start the connection.
    $('#sendmessage').click(function () {   

The “sendmessage” is the id of Button Send event.
    chat.server.send($('#displayname').val(), $('#message').val());   


Call the Send method on the hub.
    $('#message').val('').focus();   

Clear text box and reset focus for next comment. 

    function htmlEncode(value) {  
                var encodedValue = $('<div />').text(value).html();  
                return encodedValue;  
            }   


This optional function html-encodes messages for displaying in the page.

This code shows a set to open a connection with the hubs. This code starts the connection and then transfers it to a function to handle the click event on the Send button in the Chat page. 
    $('#sendmessage').click(function () {  
     chat.server.send($('#displayname').val(), $('#message').val());  
     $('#message').val('').focus();  
     });  

Step 7
Modify some code in “_Layout.cshtml” in Views > Shared folder

Code Ref 
    <!DOCTYPE html>  
    <html>  
    <head>  
        <meta charset="utf-8" />  
        <meta name="viewport" content="width=device-width, initial-scale=1.0">  
        <title>@ViewBag.Title - peter'S signalR Group Chat Application</title>  
        @Styles.Render("~/Content/css")  
        @Scripts.Render("~/bundles/modernizr")  
      
    </head>  
    <body>  
        <div class="container body-content">  
            @RenderBody()  
            <hr />  
            <footer>  
                <p>© @DateTime.Now.Year - peter'S signalR Group Chat Application</p>  
            </footer>  
        </div>  
        @Scripts.Render("~/bundles/jquery")  
        @Scripts.Render("~/bundles/bootstrap")  
        @RenderSection("scripts", required: false)  
    </body>  
    </html>   


Code Description
    <title>@ViewBag.Title - peter'S signalR Group Chat Application</title>   

This title will be shown in “Chat.Cshtml” file.
    @Styles.Render("~/Content/css")   

Link to the css file to make styles  able to View cshtml file.
    @RenderBody()   

In Layout Pages it renders the portion of content page that is not within the named section. 
    <footer>  
       <p>© @DateTime.Now.Year - peter'S signalR Group Chat Application</p>  
    </footer>   


This part will be shown in footer part of View UI.
    @Scripts.Render("~/bundles/jquery")  
    @Scripts.Render("~/bundles/bootstrap")  

This part will show you the Jquery and Bootstrap versions used in this app.
    @RenderSection("scripts", required: false)   

In layout pages , renders the content of a named section and specifies whether the section is required.

This “_Layout.cshtml” acts as a MasterPage in “Chat.cshtml” file. This file should be put in “_ViewStart.cshtml” file.

Code Ref 
    @{  
        Layout = "~/Views/Shared/_Layout.cshtml";  
    }   

Code Description

Here “_Layout.cshtml” file is used to add style format to UI of View Cshtml file.

Step 8
Then makes start page In “RouteConfig.cs” file.

Code ref 
    using System;    
    using System.Collections.Generic;    
    using System.Linq;    
    using System.Web;    
    using System.Web.Mvc;    
    using System.Web.Routing;    
        
    namespace SatyaMVCsignalR    
    {    
        public class RouteConfig    
        {    
            public static void RegisterRoutes(RouteCollection routes)    
            {    
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
        
                routes.MapRoute(    
                    name: "Default",    
                    url: "{controller}/{action}/{id}",    
                    defaults: new { controller = "Home", action = "Chat", id = UrlParameter.Optional }    
                );    
            }    
        }    
    } 


Code Description

    defaults: new { controller = "Home", action = "Chat", id=UrlParameter.Optional }  

Here Home the Controller Name and Chat the Controller Action Method Name.

Step 9

I have put my own C-Sharp Corner Profile icon file in this application as “favicon.ico”

Step 10
In “packages.config” you can check all versions of package files used in that application.

OUTPUT

The url is - http://localhost:56772/Home/Chat

Here Home the Controller Name and Chat the Controller Action Method Name.

When it loads the first time it asks for your user name.

I put my user name “peter” and clicked ok.

For “peter” I used Mozilla Firefox Browser

I put the same URL in Chrome browser and put another, New Names, to make chat conversations between “peter” names.

I opened three new tabs in Chrome browser and put the same url and put three different names, Like : KULU , KULU1 , KULU2

By using peter  I sent some message like below.

In the Chat History area it is showing what the peter user sends.

From peter : Good Morning bro….

Then using KULU , KULU1 , KULU2 user names I will send messages see what happens.
From KULU : Hey peter
From KULU1 : Hey peter
From KULU2 : Hey peter

It will show peter user message as well as KULU , KULU1 , KULU2 user messages in Chrome browser.That way every user can see every one else's sent messages in the chat history area

In Mozilla Firefox browser I will check the KULU , KULU1 , KULU2 user messages in peter user’s chat history area.
Now PETER user can see KULU , KULU1 , KULU2 user’s messages In GROUP CHAT.
Here I will show you Browser title bar text as well as Profile Icon file.



European ASP.NET MVC Hosting - HostForLIFE.eu :: Custom Model Binders in ASP.NET MVC

clock December 22, 2016 06:31 by author Scott

In ASP.NET MVC, our system is built such that the interactions with the user are handled through Actions on our Controllers. We select our actions based on the route the user is using, which is a fancy way of saying that we base it on a pattern found in the URL they’re using. If we were on a page editing an object and we clicked the save button we would be sending the data to a URL somewhat like this one.

Notice that in our route that we have specified the name of the object that we’re trying to save. There is a default Model Binder for this in MVC that will take the form data that we’re sending and bind it to a CLR objects for us to use in our action. The standard Edit action on a controller looks like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        // TODO: Add update logic here
 
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

If we were to flesh some of this out the way it’s set up here, we would have code that looked a bit like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = collection["favorite_color"];
        profile.FavoriteBoardGame = collection["FavoriteBoardGame"];

        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

What is bad about this is that we are accessing the FormCollection object which is messy and brittle. Once we start testing this code it means that we are going to be repeating code similar to this elsewhere. In our tests we will need to create objects using these magic strings. What this means is that we are now making our code brittle. If we change the string that is required for this we will have to go through our code correcting them. We will also have to find them in our tests or our tests will fail. This is bad. What we should do instead is have these only appear on one place, our model binder. Then all the code we test is using CLR objects that get compile-time checking. To create our Custom Model Binder this is all we need to do is write some code like this.

public class ProfileModelBinder : IModelBinder
{
    ProfileRepository _profileRepository = new ProfileRepository();

    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        int id = (int)controllerContext.RouteData.Values["Id"];
        Profile profile = _profileRepository.GetProfileById(id);

        profile.FavoriteColor = bindingContext
            .ValueProvider
            .GetValue("favorite_color")
            .ToString();


        profile.FavoriteBoardGame = bindingContext
            .ValueProvider
            .GetValue("FavoriteBoardGame")
            .ToString();

        return profile;
    }
}

Notice that we are using the form collection here, but it is limited to this one location. When we test we will just have to pass in the Profile object to our action, which means that we don’t have to worry about these magic strings as much, and we’re also not getting into the situation where our code becomes so brittle that our tests inhibit change. The last thing we need to do is tell MVC that when it is supposed to create a Profile object that it is supposed to use this model binder. To do this, we just need to Add our binder to the collection of binders in the Application_Start method of our GLobal.ascx.cs file. It’s done like this. We say that this binder is for objects of type Profile and give it a binder to use.

ModelBinders.Binders.Add(typeof (Profile), new ProfileModelBinder());

Now we have a model binder that should let us keep the messy code out of our controllers. Now our controller action looks like this.

[HttpPost]
public ActionResult Edit(Profile profile)
{
    try
    {
        _profileRepository.Add(profile);

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

That looks a lot cleaner to me, and if there were other things I needed to do during that action, I could do them without all of the ugly binding logic.

 



ASP.NET MVC Hosting - HostForLIFE.eu :: Using Ajax in MVC Application

clock June 21, 2016 00:16 by author Anthony

In asp.net web form application, if we need ajax service, we will need to create wcf services on server side to serve ajax calls, while in MVC web application, no wcf is needed, a controller will do.

Here are two examples (GET and POST) of how to use ajax in mvc application

Http Get example: ajax consumer in view

<script type="text/javascript">
  var user = {
                'id': 1
            };
    $.get(
                'home/getUser',
                user,
                function (data) {
                    alert(data.name);
                }
    );
</script>


Http Get example: ajax server in home controller

public class HomeController : Controller
{
    // data GET service
     public JsonResult getUser(int id)
     {
            User user = db.Users.where(u=>u.id==id)
            return Json(user,JsonRequestBehavior.AllowGet);     }
}

A few points:


Controller must return JsonResult rather than ActionResult as a normal controller does as we would want the data to be returnd as json data, and it does not have a ‘d’ wrapper

JsonRequestBehavior.AllowGet must be set in Json()call, otherwise you will get:

500 internal server error with message like

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet

You only need to set this parameter for GET and returning JSON array to avoid JSON hijacking, no need for POST requests.
Http POST example: ajax consumer in view


<script type="text/javascript">
var user={
            'name':’TheUser’,
            'age':30
        };
 $.post(
            'home/SaveUser',
            user,
            function (data) {
                if (data === true) {
                   alert('User is saved');
                }
                else {

                    alert('Failed to save the user');
                }
            },
            'json'
        );
</script>


Http POST example: ajax server in home controller

public class HomeController : Controller
{
    // data POST service
  [AcceptVerbs(HttpVerbs.Post)]
   public JsonResult SaveUser (string name, int age)
   {
        return Json(true);    }
}

A few points:

Have to decorate the controller with ‘POST’

Datatype in $.post in example is set to json, but it is not necessary to be so, if you just pass data in fields rather than in complex object. When it is not set to json it will use application/x-www-form-urlencoded as a way to pass data in standard post.


Summary:
In asp.net MVC you can use controller as ajax server without having to use wcf, compared with wcf, no configuration is needed

 

HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC Hosting - HostForLIFE.eu :: Configuring ELMAH In ASP.NET MVC

clock June 13, 2016 21:35 by author Anthony

In this article, I will integrate and setup ELMAH to asp.net MVC project. I will finish whole article in 5 different steps. ELMAH stands for Error Logging Modules and Handlers providing application wide error logging facilities. ELMAH is pluggable and easy to implement without changing single line of code. ELMAH work as interceptor of unhandled dotnet exceptions, that display over yellow screen of death. As per Author you can dynamically add ELMAH on running asp.net application without recompile or re-deploy whole application.You can download ELMAH binaries from google code or if you are using nuget then visit ELMAH nuget page.

Install

The best way to install any module to Asp.net MVC project is to use Nuget package Console. You can visit ELMAH nuget page for get latest version command.

Configure

After installing ELMAH , it will automatically update Web.Config file. If it's not so you can add following code to Web.Config file.

<configuration>
<configSections>
    <sectionGroup name="elmah">
      <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
      <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
      <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
      <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
    </sectionGroup>
</configSections>

<system.web>   
    <httpModules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
    </httpModules>
</system.web>

<system.webServer>
<modules>
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
<elmah>
    <security allowRemoteAccess="false" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="YourConnectionStringName" />
</elmah>
    <location path="elmah.axd" inheritInChildApplications="false">
    <system.web>
      <httpHandlers>
        <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
      </httpHandlers>
      <!--
      <authorization>
        <allow roles="admin" />
        <deny users="*" /> 
      </authorization>
      --> 
    </system.web>
    <system.webServer>
      <handlers>
        <add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
      </handlers>
    </system.webServer>
  </location>
</configuration>
Usage Now, It's time to use and test elmah for application. Generate exception in Home Controller
public ActionResult Index()
{
   throw new Exception("This is test Exception");
          
   return View();
}


after generating exception check your elmah like http://www.example.com/elmah.axd
Here is our output

integrate-elmah-in-aspnet-mvc

integrate elmah in asp. net mvc

Security

In addition ELMAH provides seamless security feature to prevent unauthorized access. Please read our next article to make your elmah secure.

Filtering

ELMAH identify and store exceptions in different category, you can make or edit ELMAH error screen with different filters which we will discuss in our next ELMAH series.

Notification

You can setup ELMAH email notification when any exception occurs. To unable notification option you must include below code

Add ErrorMail module
<httpModules>
    <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
</httpModules>


Add SMTP Setting
<system.net>
    <mailSettings>
        <smtp deliveryMethod="network">
            <network host="..." port="25" userName="..." password="..." />
        </smtp>
    </mailSettings>
</system.net>
 

or
<elmah>
<errorMail from="..." to="..."  async="true" smtpServer="..." smtpPort="25" userName="..." password="..." />
</elmah>

 

 


HostForLIFE.eu ASP.NET MVC Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



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