Create a simple .Net Core API

Objective

Our Objective is to create a simple .net core api that we will be using for other tutorials like Dockerizing the api and deploying to azure web api .

The complete source code of the api can be found in here in Github.

I’ve created a new .net core web api project and added new defaul controller and added some codes, see below:

[Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IConfiguration _config;
        public ValuesController(IConfiguration config)
        {
            _config = config;
        }

        [HttpGet]
        public IActionResult Get()
        {
            bool enabledLog;           
            Boolean.TryParse(_config.GetValue<string>("LogJson:Enabled"), out enabledLog);                      

            var logFolder = _config.GetValue<string>("LogJson:Path");

            var result = new
            {
                MachineName = Environment.MachineName,
                Environment = _config.GetValue<string>("ASPNETCORE_ENVIRONMENT"),
                LogJsonPath = logFolder
            };

            if (!enabledLog)
                return Ok(result);

            if (!Directory.Exists(logFolder))
            {
                Directory.CreateDirectory(logFolder);
            }

            var jsonBody = JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);

            if (jsonBody.Length > 0)
            {
                System.IO.File.WriteAllText($"{logFolder}\\{DateTime.Now.ToString("yyyyMMddHHmmss")}.json", jsonBody);
            }

            return Ok(result);
        }

The controller returns a new anonymous object with the following information: Machine name, Environment and the log folder settings (LogJson) :

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "LogJson": {
    "Path": "payloads-default",
    "Enabled": true
  }
}