MVC中使用 事物
1,MVC中所有的控制器都 继承自 Controller
2,我们要对Controller进行处理 就要写一个类来继承自Controller 重写方法 加入自己的处理程序
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CDS.CustomAttribute; using System.Transactions; namespace CDS.Manager { [HandleError] public class CDSController : Controller { #region action发生异常 /// <summary> /// action发生异常 /// </summary> /// <param name="filterContext"></param> protected override void OnException(ExceptionContext filterContext) { Session["actionException"] = ""; base.OnException(filterContext); } #endregion #region 执行action /// <summary> /// 执行action /// </summary> protected override void ExecuteCore() { if (IsTransationAction())//当前action使用事务 { using (TransactionScope scope = new TransactionScope()) { Session["actionException"] = null; base.ExecuteCore(); if (Session["actionException"] == null)//没有发生异常才提交数据库 { scope.Complete(); } Session["actionException"] = null; } }//end action使用事务 else { base.ExecuteCore(); } } #endregion #region 判断当前请求的action是否使用事务 /// <summary> /// 判断当前请求的action是否使用事务 /// </summary> /// <returns></returns> public bool IsTransationAction() { bool bTrans = false; try { ControllerContext controllerContext = new ControllerContext(new System.Web.Routing.RequestContext(HttpContext, RouteData), this); string actionName = RouteData.GetRequiredString("action"); Type tControl = controllerContext.Controller.GetType(); ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(tControl); ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName); object[] attrTrans = actionDescriptor.GetCustomAttributes(typeof(IsTransationAction), false); if (attrTrans != null && attrTrans.Length > 0 && ((CDS.CustomAttribute.IsTransationAction)(attrTrans[0])).IsTransaction) { bTrans = true; } } catch { } return bTrans; } #endregion } }
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CDS.CustomAttribute { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class IsTransationAction : Attribute { private bool b_isTransaction = false; public IsTransationAction(bool isTransaction) { this.b_isTransaction = isTransaction; } public bool IsTransaction { get { return (this.b_isTransaction); } set { this.b_isTransaction = value; } } } }