Creating A Customizable Personal Blog In ASP.NET

Introduction and Background

I don’t want to speak too much in this piece of article, instead I just want to demonstrate the presentation that I have to make today. This article is a short piece of “long report” that can be considered as an answer to most common question, “How to create a blog in ASP.NET?

Well, I find it most compelling that most people are unaware of what a blog itself is, because if they knew they could just play around with ASP.NET to build one for themselves in a night or two. In this article I will discuss a few steps that are needed to be followed while creating your own blog. I am not a good designer, so please forgive the most annoying design that you are going to witness in coming sections. But I promise I will give you an overview of a “blog in ASP.NET”. The facts that I will talk about, or the reason that you should read this article is that this article is not a “specific” how to for my own procedures. Instead, I am writing this article to give you a brief overview of what a blog is, what ASP.NET has in it for you, how you can create it and not just that, but also, how you can create a blog with all that you have. In most cases, you just have a small area for hosting with less HDD space and no database. I will cover what to do in such cases too. Just read the post.

To add some “content” I wrote a Windows 10 client application to consume the blog posts through ASP.NET Web API. I am sure in most cases this Web API thing for ASP.NET blog posts would interest you.

What is a blog, anyways?

Putting the content here simple, a blog is a place where you can share, what you want, anytime you want, with anyone you want! That is a general type of blog being used. Blog is a short form for weblog (logging, makes sense?). More specific types of blogs come depending on your content. Some of blog categories are as below:

  1. Microblogs

    Compact and straight-forward blogs. 140 characters beast, Twitter, is an example of this type.

  2. Personal blogs

    Anyone can create them and they are very much personal, demonstrating only one person. Your website can be your personal blog.

  3. Media blogs

    You can share the images, videos and other multi-media content in media blogs.

So basically a blog is just a website for sharing the content. If you ever created an online website for sharing the content, current work information, regular “diary”, then you have already worked on developing a personal blog. Blog is just a term given to online log system, where you can “log” your regular discussion topics.

So, in this article post I am going to cover a basic application that can act as a blog for someone. As an additional support I will also give you an idea of using ASP.NET’s Web API to promote your blog on native applications, such as a native Windows 10 application that loads the content from your only blog and display the blog posts to users natively.

Getting started with ASP.NET

Since most of the readers are currently not upgrading themselves to ASP.NET MVC 6, I will use ASP.NET MVC 5 (not ASP.NET 5) to show you how to do it. Things are very much similar in ASP.NET MVC 5 and ASP.NET MVC 6. The common things that I have found to change in the coming versions is that ASP.NET is now cross-platform, so if you continue to write the same application by following my article, in ASP.NET MVC 6, you will be able to run it on a server in Ubuntu, or Mac and so on. But that is not a big deal here, is it?

I will be using ASP.NET MVC 5 (not ASP.NET 5!) to demonstrate how to build your own ASP.NET personal blog. But before I get Visual Studio started, I wanted to explain the term “customizable”, which is used in the title of my current article. By the term “customizable” I mean,

  1. A blog that is entirely flexible. You can integrate plugins, or update the theme and so on.
  2. A blog that doesn’t rely on a specific third-party framework, even a data source.
  3. A blog that is built just on top of ASP.NET assemblies and doesn’t require you to do anything at all.
  4. A general blogging platform, which can be then altered to create,

    1. Social blogging service.
    2. Personal CV house
    3. Your own website to demonstrate your services
    4. So on and so forth.

In simple, the blog can be altered to your own needs and requirements. After all an ASP.NET blog is just an ASP.NET web application that you have modified to suit your own needs.

At this stage I would ask you to create a new ASP.NET project in your own machine, in the next section I will continue with the next things, like create controllers, defining the Views and so on. So, it would be good for you to create a new project at this moment and continue with the article next.

Building the application

First of all, I would like to share how I actually built the ASP.NET web application to be able to host my blog. I am going to use a web interface and an API interface, to be able to consume the blog from multiple native applications. So, I will talk about the ASP.NET programming in this section and then I will talk about the Windows 10 application programming, to actually consume the blog posts and show it to the users in a “native experience”.

Web interface controller

First of all, I will consider building the web interface to be able to showcase the blog on the internet, using a browser. This is what ASP.NET was initially developed for. To build web sites, and web applications. Web applications were introduced a bit later and then was introduced the Web API and so on. So, I am going to use the very basic concepts of ASP.NET MVC to build a simple web application that can “act” as a blog.

If you are novice to ASP.NET, because most of the times the question (in the title) is asked by a beginner in ASP.NET, so if you have no idea about ASP.NET, please read the previous posts of mine that cover ASP.NET in a great detail and would help you in understanding and learning every bit of ASP.NET programming, as from a beginner’s perspective.

  1. Understanding ASP.NET MVC using real world example, for beginners and intermediate.
  2. Novice to MVC? Read this, (ASP.NET MVC is implementation of MVC pattern of software development, this post talks about MVC not ASP.NET MVC).

I will continue to share more of my articles and posts, as the topic proceeds. I would recommend that you read the above posts if you are new to ASP.NET, most of the concepts like Controller, Views and Models may cause a confusion to you, if you are a newbie!

Almost there

I am very much fan of JSON data, I prefer using JSON over SQL databases and thus I am a fan of Newtonsoft.Json library. So, please consider installing the library before moving further. This library would be the backbone for our data source.

PM> Install-Package Newtonsoft.Json -Version 7.0.1

Once this package gets installed, please continue to the next section.

1. Build the model for application

In my case, I always prefer building the models first. This gives me an idea of building the controllers and then building the views for the application. So, I would also give you a tip, to always build the models, data structures first and then continue to build the rest of the stuff.

The model we need is just a model for the blog post. So, the structure would just be as easy as the following,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.IO;  
  6. using Newtonsoft.Json;  
  7.   
  8. namespace PersonalBlogTemplateWithServices.Models  
  9. {  
  10.      public class BlogPostModel  
  11.      {  
  12.          // General properties  
  13.          public int ID { getset; }  
  14.          public string Title { getset; }  
  15.          public string Content { getset; }  
  16.          public List<string> Tags { getset; }  
  17.   
  18.          // Time based properties  
  19.          public DateTime CreateTime { getset; }  
  20.   
  21.          // Other properties and settings may include UserID, RoleID etc.  
  22.       }  
  23.    
  24.       // The class to manage the data-sources  
  25.       public class PostManager  
  26.       {  
  27.           // Define the members  
  28.           private static string PostsFile = HttpContext.Current.Server.MapPath("~/App_Data/Posts.json");  
  29.           private static List<BlogPostModel> posts = new List<BlogPostModel>();  
  30.   
  31.           // The CRUD functions  
  32.           public static void Create(string postJson)  
  33.           {  
  34.               var obj = JsonConvert.DeserializeObject<BlogPostModel>(postJson);  
  35.   
  36.               if(posts.Count > 0)  
  37.               {  
  38.                   posts = (from post in posts  
  39.                            orderby post.CreateTime  
  40.                            select post).ToList();  
  41.                   obj.ID = posts.Last().ID + 1;  
  42.               } else  
  43.               {  
  44.                   obj.ID = 1;  
  45.               }  
  46.           }  
  47.   
  48.           posts.Add(obj);  
  49.           save();  
  50.       }  
  51.   
  52.       public static List<BlogPostModel> Read()  
  53.       {  
  54.           // Check if the file exists.  
  55.           if(!File.Exists(PostsFile))  
  56.           {  
  57.               File.Create(PostsFile).Close();  
  58.               File.WriteAllText(PostsFile, "[]"); // Create the file if it doesn't exist.  
  59.           }  
  60.           posts = JsonConvert.DeserializeObject<List<BlogPostModel>>(File.ReadAllText(PostsFile));  
  61.           return posts;  
  62.       }  
  63.   
  64.       public static void Update(int id, string postJson)  
  65.       {  
  66.           Delete(id);  
  67.           Create(postJson);  
  68.           save();  
  69.       }  
  70.   
  71.       public static void Delete(int id)  
  72.       {  
  73.           posts.Remove(posts.Find(x => x.ID == id));  
  74.           save();  
  75.       }  
  76.   
  77.       // Output function  
  78.       private static void save()  
  79.       {  
  80.           File.WriteAllText(PostsFile, JsonConvert.SerializeObject(posts));  
  81.        }  
  82.     }  
  83. }  
In the model , I have the following attributes that can be used to identify or describe the blog post at the instance.
  1. ID
  2. Title
  3. Content
  4. Tags (is an array; List)
  5. CreateTime (used to sort the items)

Great, we now have a model, and now we can continue to write the rest of the logic for our application. The model implements the CRUD functions, that we can call from external objects, from both, web interface and from Web API interface. This would allow us to manage the data layer in this class.

2. Creating the controller

Alright, first of all, create the controller. The controller would have the actions that we need to perform in our blog. Please pay attention to the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. using PersonalBlogTemplateWithServices.Models;  
  8. using Newtonsoft.Json;  
  9.   
  10. namespace PersonalBlogTemplateWithServices.Controllers  
  11. {  
  12.     public class BlogController : Controller  
  13.     {  
  14.         // GET: Blog  
  15.         public ActionResult Index()  
  16.         {  
  17.             // Read the list  
  18.             var blogs = PostManager.Read();  
  19.             if (blogs == null)  
  20.             {  
  21.                  ViewBag.Empty = true;  
  22.                  return View();  
  23.             }  
  24.             else  
  25.             {  
  26.                  // Just for sorting.  
  27.                  blogs = (from blog in blogs  
  28.                           orderby blog.CreateTime descending  
  29.                           select blog).ToList();  
  30.   
  31.                  ViewBag.Empty = false;  
  32.                  return View(blogs);  
  33.             }  
  34.         }  
  35.    
  36.         [Route("blog/read/{id}")] // Set the ID parameter  
  37.         public ActionResult Read(int id)  
  38.         {  
  39.             // Read one single blog  
  40.             var blogs = PostManager.Read();  
  41.             BlogPostModel post = null;  
  42.    
  43.             if(blogs != null && blogs.Count > 0)  
  44.             {  
  45.                 post = blogs.Find(x => x.ID == id);  
  46.             }  
  47.   
  48.             if(post == null)  
  49.             {  
  50.                 ViewBag.PostFound = false;  
  51.                 return View();  
  52.             } else  
  53.             {  
  54.                 ViewBag.PostFound = true;  
  55.                 return View(post);  
  56.             }  
  57.         }  
  58.   
  59.         public ActionResult Create()  
  60.         {  
  61.             if (Request.HttpMethod == "POST")  
  62.             {  
  63.                  // Post request method  
  64.                  var title = Request.Form["title"].ToString();  
  65.                  var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  
  66.                  var content = Request.Form["content"].ToString();  
  67.   
  68.                  // Save content  
  69.                  var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };  
  70.                  PostManager.Create(JsonConvert.SerializeObject(post));  
  71.   
  72.                  // Redirect  
  73.                  Response.Redirect("~/blog");  
  74.             }  
  75.             return View();  
  76.         }  
  77.   
  78.         [Route("blog/edit/{id}")]  
  79.         public ActionResult Edit(int id)  
  80.         {  
  81.              if(Request.HttpMethod == "POST")  
  82.              {  
  83.                  // Post request method  
  84.                  var title = Request.Form["title"].ToString();  
  85.                  var tags = Request.Form["tags"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  
  86.                  var content = Request.Form["content"].ToString();  
  87.   
  88.                  // Save content  
  89.                  var post = new BlogPostModel { Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList() };  
  90.                  PostManager.Update(id, JsonConvert.SerializeObject(post));  
  91.   
  92.                  // Redirect  
  93.                  Response.Redirect("~/blog");  
  94.              } else  
  95.              {  
  96.                  // Find the required post.  
  97.                  var post = PostManager.Read().Find(x => x.ID == id);  
  98.   
  99.                  if (post != null)  
  100.                  {  
  101.                      // Set the values  
  102.                      ViewBag.Found = true;  
  103.                      ViewBag.PostTitle = post.Title;  
  104.                      ViewBag.Tags = post.Tags;  
  105.                      ViewBag.Content = post.Content;  
  106.                  }  
  107.                  else  
  108.                  {  
  109.                      ViewBag.Found = false;  
  110.                  }  
  111.              }  
  112.   
  113.              // Finally return the view.  
  114.              return View();  
  115.          }  
  116.     }  
  117. }  
The above code, is enough! This code contains the code that you may be needing. Now, I think I need to explain the code a bit.

I have implemented the CRUD functions, in this manner, I created the functions that would allow me to create a new post, read the list of posts, read a single post at the web page or perform other functions, like update the post. You can also see, that most of the codes and functions are being called from the model. That is why, I designed the model before I created the controller. I think now you understand the importance of a model before controller.

The controller would simply capture the request, extract the data from it and then pass the data and request over to the Model. The model would then perform as per our request and return a response, which can then be sent back to the client. The purpose of such a design, is to create a web application being consumed over by Web API too. In the later sections I will consider sharing that too.

Until now, the web application is able to show us messages on the blog. If we have created a post, it will show us the post otherwise it will show us a message that there is no post currently available.

3. Creating the views

Views are simple enough to be understood easily! If you have been developing using HTML, I won’t explain them. If you haven’t, go learn!

Default page

The default page for the blog would be simple one, it would either enlist the blog posts otherwise show a message.

For this page, I would instead show the HTML code, and for the rest of the pages I will show the images, because I want to demonstrate how to use the actions.
  1. @model List<PersonalBlogTemplateWithServices.Models.BlogPostModel>  
  2. @{  
  3.     ViewBag.Title = "My Blog";  
  4. }  
  5.   
  6. @if(ViewBag.Message != null)  
  7. {  
  8.     <h4>@ViewBag.Message</h4>  
  9. }  
  10.   
  11. @if(Model == null || Model.Count == 0)  
  12. {  
  13.     <h4>Blog empty</h4>  
  14.     <p>Either under development, or author is busy. Visit back again later! :-)</p>  
  15.     <a href="~/blog/create">Create new post</a>  
  16. }  
  17. else  
  18. {  
  19.     <h4>My blog</h4>  
  20.     <p>Read my blog posts below...</p>  
  21.     // Content is available.  
  22.     <a href="~/blog/create">Create new post</a>  
  23.     foreach (var post in Model)  
  24.     {  
  25.        int tagIndex = 1;  
  26.        <h4><a href="~/blog/read/@post.ID">@post.Title</a></h4>  
  27.        <p>  
  28.        @foreach (var tag in post.Tags)  
  29.        {  
  30.            if(tagIndex == post.Tags.Count)  
  31.            {  
  32.                <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>  
  33.            }  
  34.            else  
  35.            {  
  36.                <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>  
  37.            }  
  38.   
  39.            tagIndex++;  
  40.        }  
  41.        </p>  
  42.    }  
  43. }  
The page uses the conditional values from the controller. You may have noticed the value from Controller, which is passed as a model (of type of the BlogPostModel). I have checked against that, to see if there are any posts in the data source. That is pretty much simple and straight-forward. The main thing to see, if what happens if there is a new post in the data source. Consider the next section, please!

Creating the post

When you create a new post, you follow the hyperlink, which takes you to a page where you have created a form and so on. I am not much a designer-type, so the UI is very ugly. You can make it better if you want to.

The view for “C” in “CRUD, is something like this.
  1. @{  
  2.  ViewBag.Title = "New Post";  
  3. }  
  4.   
  5. <h2>Create new blog post</h2>  
  6.   
  7. <form method="post">  
  8.     <label>Title</label>  
  9.     <input type="text" name="title" style="" class="form-control" placeholder="The headline goes here..." /><br />  
  10.     <label>Tags</label>  
  11.     <input type="text" name="tags" style="" class="form-control" placeholder="Separate each tag using a comma ','." /><br />  
  12.     <label>Content</label>  
  13.     <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?"></textarea><br />  
  14.     <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />  
  15. </form>  
Very simple though, yet powerful! Power is in your hands. Add some, or leave it if you do not want to share the admin panel with anyone. :-) Once this page gets loaded, it takes the following web page shape.

Create a new blog post page
Figure 1: Create a new blog post page. Form is filled

The above HTML takes this shape. The HTML looks clean because of hard work of:
  1. ASP.NET team for providing a template.
  2. Bootstrap guys, Twitter bootstrap is being used here (is provided along with ASP.NET template).

You can now submit the post. Alright, until now things are pretty neat and simple. Do you have any questions? Please re-read this section.

Reviewing the default page now

If you go back to the default page now, you will see that the blog would now enlist the posts (currently only 1). The following is the image, you already have the HTML for this page.

Default page showing one blog in the list
Figure 2: Default page showing one blog in the list

Now the page is able to demonstrate that we have a post, it displays the tags and name. Nothing else. After all, why would we show anything else on the default page?

Reading the blog posts, one by one

If you could read the HTML for the default page, you will see that the title of the blog post is actually a URL to the blog post, to be read. I have created the action for that (please read the controller code for Read action). This would let us now read the content,

Reading the post
Figure 3: Reading the post, shows date time, content and tags

This is how I display the content. I agree, a very bad design. But I am very bad at designing the web applications. (I know, my first attempt went wrong because IDs were null and Ah, you get it the second time, didn’t time? Quit whining!).

I used the following HTML code for this, the thing was that I just wanted to display the blog post, in a very simple way. Indeed in your case, you will write something much more useful. But, at the moment, just read this.

  1. @model PersonalBlogTemplateWithServices.Models.BlogPostModel  
  2. @{  
  3.     ViewBag.Title = Model.Title;  
  4.     var tagIndex = 1;  
  5. }  
  6.   
  7. <h4 style="font-weight: bold;">@Model.Title</h4>  
  8.   
  9. <p>@Html.Raw(Model.Content.Replace("\r\n""<br />"))</p>  
  10. <p>Posted by — Afzaal Ahmad Zeeshan — on @Model.CreateTime.ToString("MMMM dd, yyyy 'at' hh:mm tt")</p>  
  11. <p>  
  12.     Tagged under:  
  13.     @foreach (var tag in Model.Tags)  
  14.     {  
  15.         <span class="tag"><a href="~/blog/tag/@tag">@tag</a></span>  
  16.         if (tagIndex == Model.Tags.Count)  
  17.         {  
  18.             // In the end, write the edit hyperlink  
  19.             <span><a href="~/blog/edit/@Model.ID">Edit</a></span>  
  20.         }  
  21.   
  22.         // Finally increment the index  
  23.         tagIndex++;  
  24.     }  
  25. </p>  
So, this code would give us the post. I have many things hardcoded, like, “Posted by &mdash; Afzaal Ahmad Zeeshan &mdash; on {Date Time}”. You can change it, to see who is the author and so on. There are many other things to be taken care of.

One thing to understand is that your HTML is not the same that gets saved in the data source. So, you might need to re-consider the HTML, then render it using Html.Raw function. Have a look at the following code, for example,
  1. <p>@Html.Raw(Model.Content.Replace("\r\n""<br />"))</p>  
Now, each of the occurrence of “\r\n” would be replaced with the break line object in HTML. This way, you can re-build the HTML and show it as plain text on the HTML web page.

Updating the posts

The final concept that I will be talking about here would be of updating the posts. Updating is similar to creating the new post, but just that you also provide the previous data that you are having. Title, content and other stuff can be provided and then user is allowed to update them as required and then you save it back to the data source.

I have used the same HTML form in this case,
  1. @{  
  2.  ViewBag.Title = "Edit the post";  
  3.   
  4.  var tags = string.Join(", ", ViewBag.Tags as List<string>);  
  5. }  
  6.   
  7. <h2>Edit the post</h2>  
  8.   
  9. <form method="post">  
  10.     <label>Title</label>  
  11.     <input type="text" name="title" style="" class="form-control" value="@ViewBag.PostTitle" placeholder="The headline goes here..." /><br />  
  12.     <label>Tags</label>  
  13.     <input type="text" name="tags" style="" class="form-control" value="@tags" placeholder="Separate each tag using a comma ','." /><br />  
  14.     <label>Content</label>  
  15.     <textarea name="content" class="form-control" style="height: 300px;" placeholder="What would you like to write?">@ViewBag.Content</textarea><br />  
  16.     <input type="submit" style="width: auto; font-weight: 600;" value="Post" /><br />  
  17. </form>  
This is similar to what we had previously. But it renders along with the previous data we had.

HTML page
Figure 4: HTML page showing the form to edit the previously updated post

As you can see, the post contains the previous data, but also allows me to update the post. This is useful, in cases when you want to update the post. I am adding a new paragraph line, which would then be rendered as it is being written.

Tip: This is not WYSIWYG editor, just a plain-text area. You should get a WYSIWYG editor if you want to be able to use the full power of HTML in your post.

Now, once I will submit this, it would get published as this version. Please revise the controller action,
  1. if (Request.HttpMethod == "POST")  
  2. {  
  3.     // Post request method  
  4.     var title = Request.Form["title"].ToString();  
  5.     var tags = Request.Form["tags"].ToString().Split(new char[]  
  6.     {  
  7.         ','  
  8.     }, StringSplitOptions.RemoveEmptyEntries);  
  9.     var content = Request.Form["content"].ToString();  
  10.   
  11.     // Save content  
  12.     var post = new BlogPostModel  
  13.     {  
  14.         Title = title, CreateTime = DateTime.Now, Content = content, Tags = tags.ToList()  
  15.     };  
  16.     PostManager.Update(id, JsonConvert.SerializeObject(post));  
  17.   
  18.     // Redirect  
  19.     Response.Redirect("~/blog");  
  20. }  
This demonstrates, how you will update the post. Once again, we are using PostManager, the object we created in our model to be able to perform the actions. The post is now updated, have a look at the revisit to the post preview.

Updated post preview
Figure 5: Updated post preview

This now shows the updates being made. It is also clear as to how the new line is added to the post. Pretty simple it was, but I wanted to demonstrate the concept of this too.

Adding new posts

One more thing is, to add new posts. This is same, requires just a view. I am about to give you an overview of adding new posts, multiple posts and how does this preview them on the default page.

Creating a new blog post, second one
Figure 6: Creating a new blog post, second one

This is similar, the only thing to understand is how it is rendered on the blog.

Two posts being previewed
Figure 7: Two posts being previewed

The thing that I wanted to share here, is that ASP.NET won’t automatically sort the posts, you would have to do that yourself. If you pay attention to the LINQ code, you will understand it.
  1. // Just for sorting.  
  2. blogs = (from blog in blogs  
  3.          orderby blog.CreateTime descending  
  4.          select blog).ToList();  
This would now sort the blogs, a descending order. That is why, “Two posts” shows above, whereas in the JSON data it would come after the “First blog post!” But we have now sorted the list as per our requirements.

Heading over to Windows 10 application and Web API

Before I actually head over, I want to make a final post that would be read in the application! Please see the following image, then we continue to the next section.

Final post online
Figure 8: Final post online

Web interface has been discussed enough, the next sections will talk about the Web API and Windows 10 application programming.

Further reading:

If you want to get more in-depth information, please read the following documents and articles.
  1. A tip for ajax developers in ASP.NET MVC framework
  2. Getting Started with LINQ in C#

Web API and Windows 10 client application

In this section, I will first talk about the ASP.NET Web API and then I will build the application to consume the API and show the blogs. In the client application, we do not need any functions, like create, update etc. We just consume and display the data, so the client application won’t have enough functions but it would display the content.

Building the API

Actually, the API is simple and does not need anything to be done! The application has already been completed, so our API would only redirect to the application and load the data from the model and return it. API does not need to have any HTML data or CSS stylesheets, instead API just returns the data in JSON or XML format. I personally recommend and always will recommend using JSON. XML is a very heavy format and is also not efficient. JSON is much simple, lightweight and portable format!

The API is just a controller, with the same actions that we need and a return-type. Since we do not need any functions but C (from CRUD), I defined the API to be as simple as,

  1. using Newtonsoft.Json;  
  2. using PersonalBlogTemplateWithServices.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Net.Http;  
  8. using System.Web.Http;  
  9.   
  10. namespace PersonalBlogTemplateWithServices.Controllers  
  11. {  
  12.     public class BlogApiController: ApiController  
  13.     {  
  14.         // In this controller, we just need the Read functions. Nothing else!  
  15.         // We do not need the clients to be able to write or update the blogs... Just read them  
  16.   
  17.         [HttpGet]  
  18.         [Route("blog/api")]  
  19.         public List < BlogPostModel > Get()  
  20.         {  
  21.             return PostManager.Read();  
  22.         }  
  23.     }  
  24. }  
Small, but enough.This would let us consume the API from our client application. There is also no need to edit the API configuration, because I have provided the Routing scheme to the function.
  1. [Route("blog/api")]  
This would automatically get routed to this URL. The rest of the functionality is to be provided by the application.

One thing to note, is that this function again, reads the data from the model and returns is, as a collection. This would then be translated as JSON data later. So our application will be able to use the JSON converters to get the data from the API and render it on the application.

I hope things for API are clear upto this stage! If not, please re-read. I think the post is pretty much simple.

Building the client application; Windows 10 application

Great, until now you have learnt how to build the online blog that has a web interface and an API interface. I will continue with the next post, to teach you how to consume the API, the post has gone way more than I was expecting (it overwent 4k words).

Read the above article and leave your feedback, I would love to hear it!

Points of interest

Thank you for reading the post, I have shared a common, yet easy and simple way to build your own blog. The post contains the information that you may need to have to create your own online personal blog. I have not shared any third-party library because I want you to be able to add your own. The blog is built on top of native ASP.NET frameworks.

In a later post, I will also share the common concepts for building the data sources, so that the only dependency of “Newtonsoft.Json” would also be removed from this project. Until then, please bear with me.

One more thing, the text editor used is plain-text area, you can replace it with your favorite WYSIWYG editor to be able to use the power of HTML, then render the HTML on the screen.

In coming days, I will write two more posts:
  1. Consuming the Web API from Windows 10 application.
  2. Building your own custom data sources.

Stay tuned for more of such content!


Similar Articles