A Simple Blog CMS in C#

I’m not a big fan of .Net and Microsoft! Anyway, Let’s create a simple blog CMS using C# and ASP.NET Core. This will be a basic implementation to get you started.

Step 1: Set Up Your Project

  1. Create a new ASP.NET Core Web Application:

    dotnet new mvc -n SimpleBlogCMS
    cd SimpleBlogCMS
    
  2. Install Entity Framework Core:

    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools
    

Step 2: Define Your Models

Create a Models folder and add a Post class:

namespace SimpleBlogCMS.Models
{
    public class Post
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime CreatedAt { get; set; }
    }
}

Step 3: Set Up Your Database Context

Create a Data folder and add a BlogContext class:

using Microsoft.EntityFrameworkCore; using SimpleBlogCMS.Models; namespace SimpleBlogCMS.Data { public class BlogContext : DbContext { public BlogContext(DbContextOptions<BlogContext> options) : base(options) { } public DbSet<Post> Posts { get; set; } } }

Step 4: Configure Your Application

Update Startup.cs to configure the database context:

public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BlogContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); } 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.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }

Add your connection string to appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=SimpleBlogCMS;Trusted_Connection=True;MultipleActiveResultSets=true"
}

Step 5: Create Your Controllers

Create a Controllers folder and add a PostsController:

using Microsoft.AspNetCore.Mvc; using SimpleBlogCMS.Data; using SimpleBlogCMS.Models; using System.Linq; using System.Threading.Tasks; namespace SimpleBlogCMS.Controllers { public class PostsController : Controller { private readonly BlogContext _context; public PostsController(BlogContext context) { _context = context; } public async Task<IActionResult> Index() { return View(await _context.Posts.ToListAsync()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Title,Content,CreatedAt")] Post post) { if (ModelState.IsValid) { post.CreatedAt = DateTime.Now; _context.Add(post); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(post); } } }

Step 6: Create Your Views

Create a Views/Posts folder and add Index.cshtml and Create.cshtml:

Index.cshtml:

@model IEnumerable<SimpleBlogCMS.Models.Post> <h1>Blog Posts</h1> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th>Title</th> <th>Content</th> <th>Created At</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.Title</td> <td>@item.Content</td> <td>@item.CreatedAt</td> </tr> } </tbody> </table>

Create.cshtml:

@model SimpleBlogCMS.Models.Post <h1>Create New Post</h1> <form asp-action="Create"> <div class="form-group"> <label asp-for="Title" class="control-label"></label> <input asp-for="Title" class="form-control" /> <span asp-validation-for="Title" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Content" class="control-label"></label> <textarea asp-for="Content" class="form-control"></textarea> <span asp-validation-for="Content" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form>

Step 7: Run Your Application

Run the application:

dotnet run

Navigate to https://localhost:5001/Posts to see your blog CMS in action!

This is a basic implementation to get you started. You can expand it by adding features like editing and deleting posts, user authentication, and more. Happy coding! 😊


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *