MVC3动作记录机制

把网站重要的操作步骤记录下来,在ASP.NET MVC中,可以通过动作过滤器来实现。

首先在项目目录中新建一个"ActionFilter"目录,以集中管理所有的ActionFilter属性类,再新建一个ActionLogAttribute动作过滤器属性。

其中我的数据库表ActionLog结构如下图:

 

MVC3动作记录机制

ActionLogAttribute类的代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ChellonaMobileStationElectricity.Models;



namespace ChellonaMobileStationElectricity.ActionFilter

{

    public class ActionLogAttribute:ActionFilterAttribute

    {

        public string Description { get; set; }

        StationElectricEntities db;

        IMemberRepository _memberRepository;

        public ActionLogAttribute()

        {

            db = new StationElectricEntities();

            _memberRepository = new MemberRepository();

        }



        public override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            ActionLog log = new ActionLog()

            {

                UserID = _memberRepository.GetMemberByAccount(filterContext.HttpContext.User.Identity.Name).UserID,

                Action = filterContext.RouteData.Values["controller"] + "." + filterContext.RouteData.Values["action"],

                ClientIP = filterContext.HttpContext.Request.UserHostAddress,

                DesCription = this.Description

            };

            db.AddToActionLog(log);

            db.SaveChanges();

        }

    }

}

然后,我们在Controller里面就可以使用了,如下:

    [HttpPost]

        [ChellonaMobileStationElectricity.ActionFilter.ActionLog(Description="新增用户")]

        public ActionResult Create(FormCollection collection)

        {

            if (ModelState.IsValid)

            {

                User user = new User();

                user.UserName = collection["UserName"];

                user.PassWord = _memberRepository.HashPassword(collection["PassWord"]);

                user.ChName = collection["ChName"];

查下数据库,已有数据,成功。

MVC3动作记录机制

你可能感兴趣的:(mvc)