CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Đọc thông tin Metadata Attribute của Controller và Action trong ASP.NET Core 6 sử dụng Reflection

Đăng lúc: 08:35 AM - 15/11/2023 bởi Charles Chung - 588

Trong bài viết này tôi sẽ hướng dẫn các bạn đọc thông tin Metadata Attribute của Controller và Action trong ASP.NET Core 6 sử dụng Reflection.

1. Giới thiệu

  • Trong một ứng dụng .NET  bao gồm mã chương trình, dữ liệu và meta data. Meta data chính là thông tin về dữ liệu mà ứng dụng sử dụng như kiểu dữ liệu, mã thực thi, assembly...
  • Attributes là cơ chế tạo ra Metadata để chỉ thị cho trình biên dịch biết, Attribute có thể sử dụng cho interface, class, field, method,... theo mẫu [AttributeType].
  • Reflection là cách thức để truy cập tới Metadata của kiểu đối tượng bất kỳ tại lúc runtime.

Và sau đây chúng ta sẽ xem xét một ví dụ sử dụng Description Attribute để mô tả cho các Controller và Action, sau đó tại thời điểm chạy chúng ta sẽ đọc các thông tin về tên Controller, Action và Description Attribute. Việc này có thể ứng dụng vào việc phân quyền cho người dùng theo các ROLE khi truy cập và các nghiệp vụ của Website.

2. Xử lý đọc thông tin Metadata Attribute của Controller và Action

  • Tạo Project ASP.NET Core MVC 6.0 in Visual 2022
  • Tạo lớp Models/BusinessModel.cs : Bao gồm tên và mô tả của Controller và Action

namespace AspNetCoreMetadataControllerAction.Models

{

    public class BusinessModel

  {

        public string? Name { get; set; } 

        public string? Description { get; set; }

  }

}

 

  • Tạo lớp Models/ReflectionBusiness.cs : Chứa các phương thức trả về danh sách Controller và Action 

namespace AspNetCoreMetadataControllerAction.Models

{

public class ReflectionBusiness

    {

        /// <summary>

        /// Lấy tất cả các Type Controller trong 1 namespace

        /// </summary>

        /// <param name="_namespace">Tên namespace</param>

        /// <returns></returns>

        public IEnumerable<Type> GetControllers(string _namespace)

    {

            //lấy assembly chứa code đang thực thi

      Assembly assembly = Assembly.GetExecutingAssembly();

            //lấy ra các kiểu là Controller trong assembly nằm trong namesapce "_namespace"

      IEnumerable<Type> types = assembly.GetTypes()

                .Where(type => typeof(Controller).IsAssignableFrom(type)

                && type.Namespace.Contains(_namespace)).OrderBy(x => x.Name);

   return types;

    }

 

        /// <summary>

        /// Lấy tất cả các Member của một controller

        /// </summary>

        /// <param name="controller">Tên kiểu controller</param>

        /// <returns></returns>

        public IEnumerable<MemberInfo> GetActions(Type controller)

    {

IEnumerable<MemberInfo> memberInfo = controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public).Where(m => !m.GetCustomAttributes( typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any()).OrderBy(x => x.Name);

         return memberInfo;

    }

    }

}

 

  • Tạo lớp Controllers/ProductsController.cs : gồm một số các Action  và sử dụng Description Attribute để mô tả cho Controller và Action 

namespace AspNetCoreMetadataControllerAction.Controllers

{

  [Description("Quản lý sản phẩm")]

    public class ProductsController : Controller

  {

        [Description("Xem sản phẩm")]

        [HttpGet]

        public IActionResult Index()

        {

            return View();

        }

        [Description("Thêm sản phẩm")]

        [HttpGet]

        public IActionResult Create()

        {

            return View();

        }

        [Description("Lưu sản phẩm")]

        [HttpPost]

        public IActionResult Create(Object model)

        {

            return View();

        }

        [Description("Xóa sản phẩm")]

        [HttpGet]

        public IActionResult Delete()

        {

            return View();

        }

    }

}

 

  • Chỉnh sửa lớp Controllers/HomeController.cs : gồm Action Index xử lý đọc tất cả các Controller và Action trong namespace "AspNetCoreMetadataControllerAction.Controllers", đồng thời sử dụng Description Attribute để mô tả Controller và Action.

namespace AspNetCoreMetadataControllerAction.Controllers

{

    [Description("Trang quản trị")]

         public class HomeController : Controller

    {

        [Description("Đọc thông tin Controller-Action")]

        public IActionResult Index()

        {

          ReflectionBusiness reflection = new ReflectionBusiness();

            var businesses = new List<BusinessModel>();

            var controllers = reflection.GetControllers("AspNetCoreMetadataControllerAction.Controllers");

            foreach (var c in controllers)

          {

                //xử lý lấy tên và mô tả controller

                var controllerName = c.Name;

                var description = "Chưa mô tả";

                if (c.GetCustomAttributes(typeof(DescriptionAttribute), false).Length > 0)

            description= ((DescriptionAttribute)c.GetCustomAttributes(typeof(DescriptionAttribute), false).GetValue(0)).Description;

                var business1 = new BusinessModel { Name= controllerName, Description=description};

        businesses.Add(business1);

                //xử lý lấy tên và mô tả action

                var actions = reflection.GetActions(c);

                foreach (var a in actions)

        {

                    var actionName = a.Name;

                    if (a.GetCustomAttributes(typeof(DescriptionAttribute), false).Length > 0)

               description = ((DescriptionAttribute)a.GetCustomAttributes(typeof(DescriptionAttribute), false).GetValue(0)).Description;

                    var business2 = new BusinessModel { Name = controllerName+"-"+actionName, Description = description };

          businesses.Add(business2);

        }

     }

            return View(businesses);

        }

    }

}

 

  • Chỉnh sửa Views/Index.cshtml : Hiển thị danh sách Controller và Action lên màn hình.

@model IEnumerable<BusinessModel>

@{

    var i = 1;

}

<h2>DANH SÁCH CONTROLLER-ACTION</h2>

<table class="table table-bordered">

    <tr>

        <th>#</th>

        <th>Tên</th>

        <th>Mô tả</th>

    </tr>

    @foreach (var b in Model)

    {

        <tr>

            <td>@i</td>

            <td>@b.Name</td>

            <td>@b.Description</td>

        </tr>

        i++;

    }

</table>

 

  • Kết quả

alt text

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ