Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Sunday, July 18, 2021

Web API Framework - To Create Custom Filter Log file using ActionFilterAttribute class

Step1. Create an ASP.NET Web API Project.
Step2. Add the EntityFramework reference using NuGet Package Manager
Step3. Create AppDbContext class file inside the Models folder.

using System.Data.Entity;
namespace WebAPI2021.Models
{
    public class AppDbContext:DbContext
    {
        public AppDbContext()
        {
        }
        public DbSet Employees { get; set; }
    }
}
Step4. Create an Employee model inside the Models folder.

namespace WebAPI2021.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name{ get; set; }
        public int Age { get; set; }
    }
}
Step5. Add the following inside the web.config file.

<connectionstrings>
    <add connectionstring="data source=IN-AJEET-LT\SQLEXPRESS;database=APIDB;Integrated Security=SSPI" name="AppDbContext" providername="System.Data.SqlClient">
  </add></connectionstrings>
Step6. Run NuGet command: Enable-Migrations command
Step7. Run NuGet command: Add-Migration firstly
Step8. Run NuGet command: Update-database
Step9. Create a Log folder inside the project root and place a Log.txt file. Exclude the Log folder from the project and again Include the Log folder in Project.
Step10. Create ActionLogs class file inside the Models folder.

using System;
using System.IO;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPI2021.Models
{
    public class ActionLogs: ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            WriteLog(string.Format("Action method {0} is executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToString()));
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            WriteLog(string.Format("Action method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToString()));
        }
        public void WriteLog(string logText)
        {
            File.AppendAllText(HttpContext.Current.Server.MapPath("~/Log/Log.txt"),logText +"\n");
        }
    }
}
Step11. Create web API EmployeeController inside Controllers folder.

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebAPI2021.Models;

namespace WebAPI2021.Controllers
{
    [ActionLogs]
    public class EmployeeController : ApiController
    {
        public IEnumerable Get()
        {
            using (AppDbContext db = new AppDbContext())
            {
                return db.Employees.ToList();
            }
        }
        [Route("api/Employee/{id:int}")]
        public Employee Get(int id)
        {
            using (AppDbContext db = new AppDbContext())
            {
                var emp = db.Employees.FirstOrDefault(e => e.Id == id);
                return emp;
            }
        }
        [Route("api/Employee/{name}")] //template in quotes
        public Employee Get(string name)
        {
            using (AppDbContext db = new AppDbContext())
            {
                var emp = db.Employees.FirstOrDefault(e => e.Name.ToLower() == name.ToLower());
                return emp;
            }
        }
        [Route("Employee/{name}")] //template in quotes, if api/ is not needed
        public Employee GetbyName(string name)
        {
            using (AppDbContext db = new AppDbContext())
            {
                var emp = db.Employees.FirstOrDefault(e => e.Name.ToLower() == name.ToLower());
                return emp;
            }
        }
    }
}


Edited on 6th July 2023

Hot Topics