class RealA
{
public virtual string Pro { get; set; }
public virtual void ShowHello(string name)
{
Console.WriteLine($"Hello!{name},Welcome!");
}
}
//调用:
var a = new RealA();
a.Pro = "测试";
a.ShowHello("梦在旅途");
class ProxyRealA : RealA
{
public override string Pro
{
get
{
return base.Pro;
}
set
{
ShowLog("设置Pro属性前日志信息");
base.Pro = value;
ShowLog($"设置Pro属性后日志信息:{value}");
}
}
public override void ShowHello(string name)
{
try
{
ShowLog("ShowHello执行前日志信息");
base.ShowHello(name);
ShowLog("ShowHello执行后日志信息");
}
catch(Exception ex)
{
ShowLog($"ShowHello执行出错日志信息:{ex.Message}");
}
}
private void ShowLog(string log)
{
Console.WriteLine($"{DateTime.Now.ToString()}-{log}");
}
}
//调用:
var aa = new ProxyRealA();
aa.Pro = "测试2";
aa.ShowHello("zuowenjun.cn");
using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using NLog;
using NLog.Config;
using NLog.Win32.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
var test = generator.CreateClassProxy<TestA>(new TestInterceptor());
Console.WriteLine($"GetResult:{test.GetResult(Console.ReadLine())}");
test.GetResult2("test");
Console.ReadKey();
}
}
public class TestInterceptor : StandardInterceptor
{
private static NLog.Logger logger;
protected override void PreProceed(IInvocation invocation)
{
Console.WriteLine(invocation.Method.Name + "执行前,入参:" + string.Join(",", invocation.Arguments));
}
protected override void PerformProceed(IInvocation invocation)
{
Console.WriteLine(invocation.Method.Name + "执行中");
try
{
base.PerformProceed(invocation);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void PostProceed(IInvocation invocation)
{
Console.WriteLine(invocation.Method.Name + "执行后,返回值:" + invocation.ReturnValue);
}
private void HandleException(Exception ex)
{
if (logger == null)
{
LoggingConfiguration config = new LoggingConfiguration();
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
config.AddTarget("console", consoleTarget);
LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
config.LoggingRules.Add(rule1);
LogManager.Configuration = config;
logger = LogManager.GetCurrentClassLogger(); //new NLog.LogFactory().GetCurrentClassLogger();
}
logger.ErrorException("error",ex);
}
}
public class TestA
{
public virtual string GetResult(string msg)
{
string str = $"{DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss")}---{msg}";
return str;
}
public virtual string GetResult2(string msg)
{
throw new Exception("throw Exception!");
}
}
}
public abstract class Controller
{
public virtual void OnActionExecuting(MethodInfo action)
{
}
public virtual void OnActionExecuted(MethodInfo action)
{
}
public virtual void OnActionError(MethodInfo action, Exception ex)
{
}
}
public abstract class FilterAttribute : Attribute
{
public abstract string FilterType { get; }
public abstract void Execute(Controller ctrller, object extData);
}
public class ActionExecutingFilter : FilterAttribute
{
public override string FilterType => "BEFORE";
public override void Execute(Controller ctrller, object extData)
{
Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionExecutingFilter中拦截发出的消息!-{DateTime.Now.ToString()}");
}
}
public class ActionExecutedFilter : FilterAttribute
{
public override string FilterType => "AFTER";
public override void Execute(Controller ctrller, object extData)
{
Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionExecutedFilter中拦截发出的消息!-{DateTime.Now.ToString()}");
}
}
public class ActionErrorFilter : FilterAttribute
{
public override string FilterType => "EXCEPTION";
public override void Execute(Controller ctrller, object extData)
{
Console.WriteLine($"我是在{ctrller.GetType().Name}.ActionErrorFilter中拦截发出的消息!-{DateTime.Now.ToString()}-Error Msg:{(extData as Exception).Message}");
}
}
public class AppContext
{
private static readonly Type ControllerType = typeof(Controller);
private static readonly Dictionary<string, Type> matchedControllerTypes = new Dictionary<string, Type>();
private static readonly Dictionary<string, MethodInfo> matchedControllerActions = new Dictionary<string, MethodInfo>();
private Dictionary<string,string[]> routeTemplates = new Dictionary<string, string[]>();
public void AddExecRouteTemplate(string execRouteTemplate)
{
if (!Regex.IsMatch(execRouteTemplate, "{controller}", RegexOptions.IgnoreCase))
{
throw new ArgumentException("执行路由模板不正确,缺少{controller}");
}
if (!Regex.IsMatch(execRouteTemplate, "{action}", RegexOptions.IgnoreCase))
{
throw new ArgumentException("执行路由模板不正确,缺少{action}");
}
string[] keys = Regex.Matches(execRouteTemplate, @"(?<={)\w+(?=})", RegexOptions.IgnoreCase).Cast<Match>().Select(c => c.Value.ToLower()).ToArray();
routeTemplates.Add(execRouteTemplate,keys);
}
public object Run(string execRoute)
{
//{controller}/{action}/{id}
string ctrller = null;
string actionName = null;
ArrayList args = null;
Type controllerType = null;
bool findResult = false;
foreach (var r in routeTemplates)
{
string[] keys = r.Value;
string execRoutePattern = Regex.Replace(r.Key, @"{(?<key>\w+)}", (m) => string.Format(@"(?<{0}>.[^/\\]+)", m.Groups["key"].Value.ToLower()), RegexOptions.IgnoreCase);
args = new ArrayList();
if (Regex.IsMatch(execRoute, execRoutePattern))
{
var match = Regex.Match(execRoute, execRoutePattern);
for (int i = 0; i < keys.Length; i++)
{
if ("controller".Equals(keys[i], StringComparison.OrdinalIgnoreCase))
{
ctrller = match.Groups["controller"].Value;
}
else if ("action".Equals(keys[i], StringComparison.OrdinalIgnoreCase))
{
actionName = match.Groups["action"].Value;
}
else
{
args.Add(match.Groups[keys[i]].Value);
}
}
if ((controllerType = FindControllerType(ctrller)) != null && FindAction(controllerType, actionName, args.ToArray()) != null)
{
findResult = true;
break;
}
}
}
if (findResult)
{
return Process(ctrller, actionName, args.ToArray());
}
else
{
throw new Exception($"在已配置的路由模板列表中未找到与该执行路由相匹配的路由信息:{execRoute}");
}
}
public object Process(string ctrller, string actionName, params object[] args)
{
Type matchedControllerType = FindControllerType(ctrller);
if (matchedControllerType == null)
{
throw new ArgumentException($"未找到类型为{ctrller}的Controller类型");
}
object execResult = null;
if (matchedControllerType != null)
{
var matchedController = (Controller)Activator.CreateInstance(matchedControllerType);
MethodInfo action = FindAction(matchedControllerType, actionName, args);
if (action == null)
{
throw new ArgumentException($"在{matchedControllerType.FullName}中未找到与方法名:{actionName}及参数个数:{args.Count()}相匹配的方法");
}
var filters = action.GetCustomAttributes<FilterAttribute>(true);
List<FilterAttribute> execBeforeFilters = new List<FilterAttribute>();
List<FilterAttribute> execAfterFilters = new List<FilterAttribute>();
List<FilterAttribute> exceptionFilters = new List<FilterAttribute>();
if (filters != null && filters.Count() > 0)
{
execBeforeFilters = filters.Where(f => f.FilterType == "BEFORE").ToList();
execAfterFilters = filters.Where(f => f.FilterType == "AFTER").ToList();
exceptionFilters = filters.Where(f => f.FilterType == "EXCEPTION").ToList();
}
try
{
matchedController.OnActionExecuting(action);
if (execBeforeFilters != null && execBeforeFilters.Count > 0)
{
execBeforeFilters.ForEach(f => f.Execute(matchedController, null));
}
var mParams = action.GetParameters();
object[] newArgs = new object[args.Length];
for (int i = 0; i < mParams.Length; i++)
{
newArgs[i] = Convert.ChangeType(args[i], mParams[i].ParameterType);
}
execResult = action.Invoke(matchedController, newArgs);
matchedController.OnActionExecuted(action);
if (execBeforeFilters != null && execBeforeFilters.Count > 0)
{
execAfterFilters.ForEach(f => f.Execute(matchedController, null));
}
}
catch (Exception ex)
{
matchedController.OnActionError(action, ex);
if (exceptionFilters != null && exceptionFilters.Count > 0)
{
exceptionFilters.ForEach(f => f.Execute(matchedController, ex));
}
}
}
return execResult;
}
private Type FindControllerType(string ctrller)
{
Type matchedControllerType = null;
if (!matchedControllerTypes.ContainsKey(ctrller))
{
var assy = Assembly.GetAssembly(typeof(Controller));
foreach (var m in assy.GetModules(false))
{
foreach (var t in m.GetTypes())
{
if (ControllerType.IsAssignableFrom(t) && !t.IsAbstract)
{
if (t.Name.Equals(ctrller, StringComparison.OrdinalIgnoreCase) || t.Name.Equals($"{ctrller}Controller", StringComparison.OrdinalIgnoreCase))
{
matchedControllerType = t;
matchedControllerTypes[ctrller] = matchedControllerType;
break;
}
}
}
}
}
else
{
matchedControllerType = matchedControllerTypes[ctrller];
}
return matchedControllerType;
}
private MethodInfo FindAction(Type matchedControllerType, string actionName, object[] args)
{
string ctrlerWithActionKey = $"{matchedControllerType.FullName}.{actionName}";
MethodInfo action = null;
if (!matchedControllerActions.ContainsKey(ctrlerWithActionKey))
{
if (args == null) args = new object[0];
foreach (var m in matchedControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
if (m.Name.Equals(actionName, StringComparison.OrdinalIgnoreCase) && m.GetParameters().Length == args.Length)
{
action = m;
matchedControllerActions[ctrlerWithActionKey] = action;
break;
}
}
}
else
{
action = matchedControllerActions[ctrlerWithActionKey];
}
return action;
}
}
public class TestController : Controller
{
public override void OnActionExecuting(MethodInfo action)
{
Console.WriteLine($"{action.Name}执行前,OnActionExecuting---{DateTime.Now.ToString()}");
}
public override void OnActionExecuted(MethodInfo action)
{
Console.WriteLine($"{action.Name}执行后,OnActionExecuted--{DateTime.Now.ToString()}");
}
public override void OnActionError(MethodInfo action, Exception ex)
{
Console.WriteLine($"{action.Name}执行,OnActionError--{DateTime.Now.ToString()}:{ex.Message}");
}
[ActionExecutingFilter]
[ActionExecutedFilter]
public string HelloWorld(string name)
{
return ($"Hello World!->{name}");
}
[ActionExecutingFilter]
[ActionExecutedFilter]
[ActionErrorFilter]
public string TestError(string name)
{
throw new Exception("这是测试抛出的错误信息!");
}
[ActionExecutingFilter]
[ActionExecutedFilter]
public int Add(int a, int b)
{
return a + b;
}
}
class MVCProgram
{
static void Main(string[] args)
{
try
{
var appContext = new AppContext();
object rs = appContext.Process("Test", "HelloWorld", "梦在旅途");
Console.WriteLine($"Process执行的结果1:{rs}");
Console.WriteLine("=".PadRight(50, '='));
appContext.AddExecRouteTemplate("{controller}/{action}/{name}");
appContext.AddExecRouteTemplate("{action}/{controller}/{name}");
object result1 = appContext.Run("HelloWorld/Test/梦在旅途-zuowenjun.cn");
Console.WriteLine($"执行的结果1:{result1}");
Console.WriteLine("=".PadRight(50, '='));
object result2 = appContext.Run("Test/HelloWorld/梦在旅途-zuowenjun.cn");
Console.WriteLine($"执行的结果2:{result2}");
Console.WriteLine("=".PadRight(50, '='));
appContext.AddExecRouteTemplate("{action}/{controller}/{a}/{b}");
object result3 = appContext.Run("Add/Test/500/20");
Console.WriteLine($"执行的结果3:{result3}");
object result4 = appContext.Run("Test/TestError/梦在旅途-zuowenjun.cn");
Console.WriteLine($"执行的结果4:{result4}");
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"发生错误:{ex.Message}");
Console.ResetColor();
}
Console.ReadKey();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有