31 Oct 2021 - by 'Maurits van der Schee'
In 2015 I was working on a Simple C# web framework for .NET. Back then I wanted to create an MVC framework that would allow me to run C# web applications on Linux. Back then I was using MonoDevelop to work on C# code for Mono. Today in 2021 I'm using Visual Studio Code to write C# code for .NET 5 (still on Linux). This port aims to take full advantage of the new .NET 5 platform and it's support for Linux. I am especially interested in cross-platform support and creating single executable web applications (like Go can do with go-bindata-assetfs).
I tried to sum up the goals for the project as bullet points:
Thankfully .NET 5 makes it really easy to achieve those goals.
On Ubuntu 20.04 you need to execute:
wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb \
-O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb
Then install the needed packages using:
sudo apt-get update; \
sudo apt-get install -y apt-transport-https && \
sudo apt-get update && \
sudo apt-get install -y dotnet-sdk-5.0
Source: https://docs.microsoft.com/en-us/dotnet/core/install/linux-ubuntu
Now you have the dotnet
command on your command line and I would recommend that you install Visual Studio Code and it's C# extension.
Would you like to play with this minimalistic MVC framework? First you need to clone the example project:
git clone https://github.com/maussoft/mvc-example-cs
Now you have the following directories in your project directory:
Now let me show you how to add some code.
Our webserver uses the following session class in Session.cs
:
using System.Collections.Generic;
public class Session
{
public List<string> Names { get; set; }
public Session()
{
this.Names = new List<string>();
}
}
This Session class can hold names in a list.
Now let's create a simple controller in Controllers/Hello.cs
:
using Maussoft.Mvc;
namespace Acme.Example.Controllers
{
public class Hello
{
public void World(WebContext<Session> context, string name)
{
context.Session.Names.Add(name);
context.Data.Names = context.Session.Names.ToArray();
}
}
}
The create a Layout in Views/Layouts/Hello.aspx
:
<%@ Master %>
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<body>
<% RenderViewContent(); %>
</body>
</html>
And a view in Views/Hello/World.aspx
:
<%@ Page Inherits="Layouts.Hello" %>
<h1>Names</h1>
<ul>
<% foreach (var name in Context.Data.Names) { %>
<li><%= name %></li>
<% } %>
</ul>
And then run the application using:
dotnet run
And access it on:
http://localhost:2345/Hello/World/Maurits
You will see an increasing list of names (stored in the session).
Source code: https://github.com/maussoft/mvc
Happy programming!
PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.