.Net Core Web API

Let’s Ready a .Net Core Web API Project

Choosing the right framework for writing Web Services/APIs is essential part before start development. The goal of the APIs is to centralize the data to make it available for all the clients’ applications. That’s one of the reasons that .Net Core is always considered when we required high performance, scalable, maintainable & well documented Web APIs.

There’re many great tutorials to learn writing Web Services in .Net Core, but in this article, I’m going to discuss prerequisites or some necessary setup before writing Powerful API using .Net Core Web API.

Let’s have a quick look at what we’ll cover to ready an ASP.Net Core Web API Project.

Table of Content

Security checklist

Security of any Web Services is really important because of its public access via a URL or any IP Address. Before writing Web Services you need to consider some security best practices.

Always submit sensitive data using Encryption: Keep in mind that never submit your Passwords or any other sensitive data in original format to the server using your API. Hackers can steal your information from the network. So, always use an encryption algorithm at the client-side & then decrypt these data again on the server-side.

Never display original Technical error to the End-User: You should log your complete exception with original exception message for debugging purpose in a file on the server but always return a custom message to the end-user. e.g. There’s a problem, please try later. An original technical error message can help an Attacker to provide the information about your application code.

Never keep sensitive data in clear form in your Database: Someone can also access your database due to less secure server access. So, you should always store Passwords or sensitive data like users` bank account details in hashed or encrypted form.

Try to Hide your .Net Core Version: Make things more difficult for hackers & Hide your .Net Core Version because every HTTP response contains the information about the .Net version you’re using.

LINQ can protect from SQL Injection: Linq is a great way to keep yourself secure from SQL Injections. So use Linq for your database queries & always validate user on the server-side.

Always use SSL: SSL provides Secure Socket for Client/Server communication using encryption. So always use SSL on your server.

Always keep your Framework & Libraries Updated: Old Framework & Libraries versions also creates holes for the attackers. Always use updated versions of Frameworks & Libraries.

Creating a Project

Our first step will be creating a .Net Core Web API Project. I don’t prefer to create an Empty project, Instead create a new project with WebAPI Template helps us to save time. I’m going to use the VS Code with dotnet CLI for creating our project. Let’s first create a new Folder as WebAPI & open that folder in your VS Code Editor.

Best Cross-Platform .NET Core IDE for Windows | MacOS | Linux

Open VS Code Terminal & run this command

dotnet new webapi

A new project will be created with a template like this.

you can see that we already have a ValuesController.cs which will already have some APIs with the dummy data.

Setting up Swagger

Swagger is a great tool for Automatically generating API Documentation. Developers hate to document their APIs for client applications developers who want to consume the APIs.

We need to install the Swagger Nuget Package for Asp.Net Core using this Command.

dotnet add package Swashbuckle.AspNetCore

Open Startup.cs file & Add the below code in your ConfigureServices Method after services.AddMvc()

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});

Now, add the below code inside your Configure Method of your Startup.cs class.

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

Run your project & go to this URL:

https://localhost:5001/swagger

Your URL might be different with different port.

You’ll see Swagger UI with all your APIs in ValuesController

Here’s a detailed article on .Net Core API Documentation.

Error Logging using NLog

There are many Libraries available for Error logging but NLog considered one of the best available libraries, it’s easy to setup & provides many methods to create & store logs. NLog is available at Nuget. You can install it using your prefered way. I’m going to use the .Net CLI. So, here’s the command to install NLog.

dotnet add package NLog

Now add a new configuration file at the root of your project with the name as “NLog.config” & paste this Code

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="logfile" xsi:type="File" fileName="Logs.txt" />
        <target name="logconsole" xsi:type="Console" />
    </targets>
    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

Now, you should add try-catch in all your API methods & use NLog like this

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using NLog;

namespace WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        [HttpGet]
        public ActionResult<IEnumerable<string>> MyAPI()
        {
            try
            {
                // API code
            }
            catch (System.Exception e)
            {
                logger.Debug(e);
            }
            return new string[] { "value1", "value2" };
        }
    }
}

logger.Debug(e); will log detailed logs in a log file in case of an Exception in your API.

Here’s a detailed article of ASP.Net Core Error Logging

Setting up Caching

LazyCach is one of the easiest to use Cache library available for .Net Core with great results.

How I Boosted My Asp.net Core App & Api Performance 250% By Caching

A NuGet package is available, so you can install it the way you like. I’m again going to use dotnet CLI.

dotnet add package LazyCache

How it works

When we cache any Database query results, it stores that it caches & check for the change in the result in next request. In case of same results found, cached results are returned instead of getting all records from DB again.

Here’s the example Code of caching a database query.

return Ok(cache.GetOrAdd("all-users", () => db.Users.ToList()));

Setting up Token Authentication

JWT(JSON Web Token) is a great library for Token-based Authentication. I’m not going to implement it here otherwise this article will become so long. So, here’s the step by step guide to implement JWT in your API Project

For now, I’m going to close this Article. I hope It was helpful.

Here’re some more related articles:

– WHAT STATS AND SURVEYS ARE SAYING ABOUT .NET CORE IN 2020

– HOW I BOOSTED MY ASP.NET CORE APP & API PERFORMANCE 250% BY CACHING

– TOP OPEN SOURCE ASP.NET CORE CONTENT MANAGEMENT SYSTEM (CMS)

Author

I'm passionate about learning new technologies as well as mentoring and helping others get started with their programming career. This blog is my way of giving back to the Community.

Write A Comment