(精华)2020年10月21日 设计模式案例 AspNetCore运行原理

举报
愚公搬代码 发表于 2021/10/19 22:50:21 2021/10/19
【摘要】 AspNetCore运行原理 #region { // 完成一个请求 /*// 1、加载Controller EndpointRouteBuilder endpointRoute...

AspNetCore运行原理

#region
{
    // 完成一个请求
    /*// 1、加载Controller
    EndpointRouteBuilder endpointRouteBuilder = new EndpointRouteBuilder();
    endpointRouteBuilder.MapControllers();// 扫描所有Controller

    // 2、创建EndpointRoute
    EndpointRoute endpointRoute = new EndpointRoute();
    Endpoint endpoint = endpointRoute.Match("/index");

    // 3、执行Endpoint
    EndpointHandler endpointHandler = new EndpointHandler();
    object result = endpointHandler.HandlerEndpoint(endpoint, new object[] { "原理解析" });

    // 4、对结果进行处理*/
    EndpointMiddlewareFacde endpointMiddlewareFacde = new EndpointMiddlewareFacde();
    endpointMiddlewareFacde.Invoke(new HttpContext());

}
#endregion

Endpoint相关类

/// <summary>
    /// 端点(就是Action的抽象)
    /// </summary>
    class Endpoint
    {
        /// <summary>
        /// 方法信息
        /// </summary>
        public MethodInfo methodInfo { set; get; }

        /// <summary>
        /// 方法参数
        /// </summary>
        public IList<ParameterInfo> parameterInfos { set; get; }

        /// <summary>
        /// 方法返回值
        /// </summary>
        public object returnValue { set; get; }

        /// <summary>
        /// 控制器
        /// </summary>
        public object Controller { set; get; }

    }
/// <summary>
    /// Endpoint数据源(存储Endpoint数据集合)
    /// </summary>
    class EndpointDataSources
    {
        /// <summary>
        /// Endpoint 集合
        /// </summary>
        public IDictionary<string, Endpoint> endpoints { set; get; } = new Dictionary<string, Endpoint>();
    }
/// <summary>
    /// 端点处理
    /// </summary>
    class EndpointHandler
    {
        /// <summary>
        /// 执行端点
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="providedArgs">方法参数值</param>
        /// <returns></returns>
        public object HandlerEndpoint(Endpoint endpoint,object[] providedArgs)
        {
            // 1、获取方法
            MethodInfo methodInfo = endpoint.methodInfo;

            // 2、执行
            return methodInfo.Invoke(endpoint.Controller, providedArgs);
        }
    }
/// <summary>
    /// Endpoint 路由(根据路径进行匹配Endpoint)
    /// </summary>
    class EndpointRoute
    {
        public EndpointRouteBuilder endpointRouteBuilder { set; get; }

        public Endpoint Match(string requestPath) {
            // 匹配合适的Endpoint
            return endpointRouteBuilder.Build().endpoints[requestPath];
        }
    }
/// <summary>
    /// 构建EndpointDataSources(建造者设计模式)
    /// </summary>
    class EndpointRouteBuilder
    {
        /// <summary>
        /// Endpoint集合
        /// </summary>
        private EndpointDataSources endpointDataSources = new EndpointDataSources();

        /// <summary>
        /// 1、加载Controller类和相关特性
        /// </summary>
        public void MapControllers()
        {
            // 1、解析controller 和action 装换成Endpoint(反射加载)
            Endpoint endpoint = new Endpoint();
            endpoint.methodInfo = typeof(EndpointRouteBuilder).GetMethods()[0];

            // 2、添加到端点集合
            endpointDataSources.endpoints.Add("/index.html", endpoint);
        }

        /// <summary>
        /// 2、加载RazorPage页面Endpoint
        /// </summary>
        public void MapRazorPages()
        {
        }

        public EndpointDataSources Build()
        {
           return endpointDataSources;
        }
    }
/// <summary>
    /// http上下文类(用于获取HttpRequest和HttpResponse)
    /// </summary>
    class HttpContext
    {

    }

适配器日志相关类

log4

/// <summary>
    /// Log4j日志输出
    /// </summary>
    class Log4jLog : ILog
    {
        // Log4j日志
        private log4net.ILog log;

        public Log4jLog(log4net.ILog log)
        {
            // 1、创建log4j日志
            this.log = log;
        }

        public void Debug(string msg)
        {
            log.Debug(msg);
        }

        public void Error(string msg)
        {
            log.Error(msg);
        }

        public void Info(string msg)
        {
            log.Info(msg);
        }

        public void Warn(string msg)
        {
            log.Warn(msg);
        }
    }
/// <summary>
    /// Log适配器,将log4j和Nlog转换成为需要的ILog
    /// </summary>
    class Log4NetLogAdpater : ILogAdpater
    {
        public ILog GetLog(Type type)
        {
            NLog.Logger logger = NLog.LogManager.GetLogger("product", type);
            return new NLogLog(logger);
        }
    }

NLog

/// <summary>
    /// Log适配器,将log4j和Nlog转换成为需要的ILog
    /// </summary>
    class NLogILogAdpater : ILogAdpater
    {
        public ILog GetLog(Type type)
        {
            NLog.Logger logger = NLog.LogManager.GetLogger("product", type);
            return new NLogLog(logger);
        }
    }
/// <summary>
    /// NLog日志输出
    /// </summary>
    class NLogLog : ILog
    {
        // NLog 日志
        private NLog.Logger logger; 

        public NLogLog(Logger logger)
        {
            // 1、创建日志
            this.logger = logger;
        }

        public void Debug(string msg)
        {
            logger.Debug(msg);
        }

        public void Error(string msg)
        {
            logger.Error(msg);
        }

        public void Info(string msg)
        {
            logger.Info(msg);
        }

        public void Warn(string msg)
        {
            logger.Warn(msg);
        }
    }

日志工厂

/// <summary>
    /// 自定义日志输出
    /// </summary>
    interface ILog
    {
        public void Debug(string msg);
        public void Info(string msg);
        public void Warn(string msg);
        public void Error(string msg);
    }
/// <summary>
    /// Log适配器,将log4j和Nlog转换成为需要的ILog
    /// </summary>
    interface ILogAdpater
    {
        public ILog GetLog(Type type);
    }
/// <summary>
    /// 日志工厂
    /// </summary>
    class LogFactory
    {
        public ILog GetLog(string loggerFlag,Type type)
        {
            if ("log4net".Equals(loggerFlag))
            {
                return new Log4NetLogAdpater().GetLog(type);
            } else if ("nlog".Equals(loggerFlag))
            {
                return new NLogILogAdpater().GetLog(type);
            }
            return null;
        }
    }

节点中间件

/// <summary>
    /// 终结点中间件(外观模式)
    /// </summary>
    class EndpointMiddlewareFacde
    {
        private EndpointRouteBuilder endpointRouteBuilder;
        private EndpointRoute endpointRoute;
        private EndpointHandler endpointHandler;

        public EndpointMiddlewareFacde()
        {
            this.endpointRouteBuilder = new EndpointRouteBuilder();
            this.endpointRoute = new EndpointRoute();
            this.endpointHandler = new EndpointHandler();
        }

        /// <summary>
        /// 执行请求
        /// </summary>
        /// <param name="httpContext"></param>
        public void Invoke(HttpContext httpContext)
        {
            // 1、加载Controller
            endpointRouteBuilder.MapControllers();// 扫描所有Controller

            // 2、创建EndpointRoute
            Endpoint endpoint = endpointRoute.Match("/index");

            // 3、执行Endpoint
            object result = endpointHandler.HandlerEndpoint(endpoint, new object[] { "原理解析" });

            // 4、对结果进行处理(就是将数据输出到页面)
            ViewResult viewResult = (ViewResult)result;

            // 5、输出到页面
            if (viewResult.ViewType.Equals("Razor"))
            {
                // 5.1 输出到Razor页面
                RazorView razorView = new RazorView();
                razorView.Render(viewResult.ViewData, httpContext);
            } else if (viewResult.ViewType.Equals("XML"))
            {
                // 5.2 输出到XML页面
                XMLView xMLView = new XMLView();
                xMLView.Render(viewResult.ViewData, httpContext);
            }
        }
       
    }

view相关

/// <summary>
    ///视图模板
    /// </summary>
    abstract class AbstractView 
    {
        /// <summary>
        /// 渲染方法
        /// </summary>
        /// <param name="viewData"></param>
        /// <param name="httpContext"></param>
        public void Render(IDictionary<string, object> viewData, HttpContext httpContext)
        {
            // 1、转换成Razor数据
            TransformData(viewData);

            // 2、构建Razor页面
            BuildPage(viewData);

            // 3、输出Razor页面
            WritePage(httpContext);
        }


        protected abstract void TransformData(IDictionary<string, object> viewData);

        protected abstract void BuildPage(IDictionary<string, object> viewData);

        protected abstract void WritePage(HttpContext httpContext);

    }
/// <summary>
    /// 数据输出到页面,Razor页面,Asp页面
    /// </summary>
    interface IView
    {
        /// <summary>
        /// 视图渲染
        /// </summary>
        /// <param name="viewData"></param>
        /// <param name="httpContext"></param>
       public void Render(IDictionary<string,object> viewData,HttpContext httpContext);
    }
/// <summary>
    /// Razor 视图页面
    /// </summary>
    class RazorView : AbstractView
    {
       /* public  void Render(IDictionary<string, object> viewData, HttpContext httpContext)
        {
            // 1、转换成Razor数据
            TransformRazorData(viewData);

            // 2、构建Razor页面
            BuildRazorPage(viewData);

            // 3、输出Razor页面
            WritePazorPage(httpContext);
        }*/

        protected override void TransformData(IDictionary<string, object> viewData)
        {
            Console.WriteLine($"将数据转换成Razor数据");
        }

        protected override void BuildPage(IDictionary<string, object> viewData)
        {
            Console.WriteLine($"构造Razor页面");
        }

        protected override void WritePage(HttpContext httpContext)
        {
            Console.WriteLine($"输出Razor页面");
        }
       
       
    }
/// <summary>
    /// Action执行结果
    /// </summary>
    class ViewResult
    {
        // 1、页面需要数据
        public IDictionary<string, object> ViewData { set; get; }

        // 2、视图名称
        public string ViewName {set;get;}

        // 3、视图类型
        public string ViewType { set; get; }
    }
/// <summary>
    /// xml视图
    /// </summary>
    class XMLView:AbstractView
    {

        /*public void Render(IDictionary<string, object> viewData, HttpContext httpContext)
        {
            // 1、转换成Razor数据
            TransformXMLData(viewData);

            // 2、构建Razor页面
            BuildXMLPage(viewData);

            // 3、输出Razor页面
            WriteXMLPage(httpContext);
        }*/


        protected override void TransformData(IDictionary<string, object> viewData)
        {
            Console.WriteLine($"将数据转换成Razor数据");
        }

        protected override void BuildPage(IDictionary<string, object> viewData)
        {
            Console.WriteLine($"构造Razor页面");
        }

        protected override void WritePage(HttpContext httpContext)
        {
            Console.WriteLine($"输出Razor页面");
        }
    }

文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。

原文链接:codeboy.blog.csdn.net/article/details/109203902

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。