.NET MVC5简介(二)
mvcapplication---application_statr--registerroutes--给routecollection添加规则,请求进到网站---x----请求地址被路由按照顺序匹配,遇到一个温和的就结束,就到对应的控制器和action。
在程序中使用log4net,首先nuget引入程序集
logger代码
public class logger { static logger() { xmlconfigurator.configure(new fileinfo(path.combine(appdomain.currentdomain.basedirectory, "cfgfiles\\log4net.config"))); ilog log = logmanager.getlogger(typeof(logger)); log.info("系统初始化logger模块"); } private ilog loger = null; public logger(type type) { loger = logmanager.getlogger(type); } /// <summary> /// log4日志 /// </summary> /// <param name="msg"></param> /// <param name="ex"></param> public void error(string msg = "出现异常", exception ex = null) { console.writeline(msg); loger.error(msg, ex); } /// <summary> /// log4日志 /// </summary> /// <param name="msg"></param> public void warn(string msg) { console.writeline(msg); loger.warn(msg); } /// <summary> /// log4日志 /// </summary> /// <param name="msg"></param> public void info(string msg) { console.writeline(msg); loger.info(msg); } /// <summary> /// log4日志 /// </summary> /// <param name="msg"></param> public void debug(string msg) { console.writeline(msg); loger.debug(msg); } }
配置文件log4net.config
<?xml version="1.0" encoding="utf-8"?> <log4net> <!-- define some output appenders --> <appender name="rollingappender" type="log4net.appender.rollingfileappender"> <file value="log\log.txt" /> <!--追加日志内容--> <appendtofile value="true" /> <!--防止多线程时不能写log,官方说线程非安全--> <lockingmodel type="log4net.appender.fileappender+minimallock" /> <!--可以为:once|size|date|composite--> <!--composite为size和date的组合--> <rollingstyle value="composite" /> <!--当备份文件时,为文件名加的后缀--> <datepattern value="yyyymmdd.txt" /> <!--日志最大个数,都是最新的--> <!--rollingstyle节点为size时,只能有value个日志--> <!--rollingstyle节点为composite时,每天有value个日志--> <maxsizerollbackups value="20" /> <!--可用的单位:kb|mb|gb--> <maximumfilesize value="3mb" /> <!--置为true,当前最新日志文件名永远为file节中的名字--> <staticlogfilename value="true" /> <!--输出级别在info和error之间的日志--> <filter type="log4net.filter.levelrangefilter"> <param name="levelmin" value="info" /> <param name="levelmax" value="fatal" /> </filter> <layout type="log4net.layout.patternlayout"> <conversionpattern value="%date [%thread] %-5level %logger - %message%newline"/> </layout> </appender> <!-- levels: off > fatal > error > warn > info > debug > all --> <root> <priority value="all"/> <level value="all"/> <appender-ref ref="rollingappender" /> </root> </log4net>
public class mvcapplication : system.web.httpapplication { private logger logger = new logger(typeof(mvcapplication)); protected void application_start() { arearegistration.registerallareas();//注册区域 filterconfig.registerglobalfilters(globalfilters.filters);//注册全局的filter routeconfig.registerroutes(routetable.routes);//注册路由 bundleconfig.registerbundles(bundletable.bundles);//合并压缩 ,打包工具 combres this.logger.info("网站启动了。。。"); } }
area
area请参考博客:
有时候因为一个web项目可以非常大非常复杂,多人合作开发,命名就成问题了。area可以把项目拆分开,方便团队合作,演变到后面就可以做成插件式开发了:
mvcapplication--application_start--arearegistration.registerallareas()---其实就是把systemarearegistration给注册下---添加url地址规则--请求来了就匹配(area在普通的之前)
众所周知,mvc请求的最后是反射调用controller+action,信息来自于url+roy=ute,路由匹配时,只能找到action和controller,其实还有个步骤,扫描+存储,在bin里面找controller的子类,然后把命名空间---类名称+方法全部存起来。
控制器类可以出现在mvc项目之外,唯一的规则就是继承自controller,area也可以独立开,规则是必须有个继承arearegistration。
public class systemarearegistration : arearegistration { public override string areaname { get { return "system"; } } public override void registerarea(arearegistrationcontext context) { context.maproute( name: "system_default", url: "system/{controller}/{action}/{id}", defaults: new { action = "index", id = urlparameter.optional } ); } }
razor语法:cshtml本质是一个类文件,混编了html+cs代码
写后台代码:行内--单行--多行--关键字
后台代码写html:@: 闭合的html标签 <text></text>
html扩展控件:封装个方法,自动生成html
后端一次性完成全部内容,而且html标签闭合
我们还可以自行封装这种扩展方法
但是这个已经不流行了,就是ui改动需要重新发布
更多应该是前后分离,写前端的人是不会懂后端的写法
layout
masterpage--layout 默认是_layout 可以自行指定
@styles.render("~/content/css") 使用样式包
@scripts.render("~/bundles/modernizr") 使用js包
@renderbody() 就是页面的结合点
@rendersection("scripts", required: false)
partialpage局部页---ascx控件,是没有自己的action
@{ html.renderpartial("partialpage", "这里是html.renderpartial"); }
@html.partial("partialpage", "这里是html.partial")
子请求
@html.action("childaction", "second", new { name = "html.action" })
@{html.renderaction("childaction", "second", new { name = "html.renderaction" });}
有action,也可以传参数
[childactiononly]//只能被子请求访问 不能独立访问
asp.net mvc中html.partial, renderpartial, action,renderaction 区别和用法请参考
route
其实,路由这个东西,如果没必要的话,还是不要随便乱改了
下面是路由的一些改动:
public class routeconfig { public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); //忽略路由 正则表达式 {resource}表示变量 a.axd/xxxx resource=a pathinfo=xxxx //.axd是历史原因,最开始都是webform,请求都是.aspx后缀,iis根据后缀转发请求;mvc出现了,没有后缀,iis6以及更早版本,打了个补丁,把mvc的请求加上个.axd的后缀,然后这种都转发到网站----新版本的iis已经不需要了,遇到了就直接忽略,还是走原始流程 routes.ignoreroute("customservice/{*pathinfo}");//以customservice开头,都不走路由 routes.maproute( name: "about", url: "about", defaults: new { controller = "home", action = "about", id = urlparameter.optional } );//固定路由,/home/about----about routes.maproute( name: "test", url: "test/{action}/{id}", defaults: new { controller = "second", action = "index", id = urlparameter.optional } );//修改控制器, routes.maproute( name: "regex", url: "{controller}/{action}_{year}_{month}_{day}", defaults: new { controller = "second", action = "index", id = urlparameter.optional }, constraints: new { year = @"\d{4}", month = @"\d{2}", day = @"\d{2}" } ); //http://localhost:2017/second/time_2019_06_13 regex //http://localhost:2017/second/time_2019_6_13 失败 //http://localhost:2017/second/time?year=2019&month=6&day=13 default //http://localhost:2017/test/time?year=2019&month=6&day=13 test //http://localhost:2017/test/time_2019_06_13 失败的,只会被一个路由匹配 //常规路由,一般来说,我们不怎么扩展这个路由 routes.maproute( name: "default",//路由名称,routecollection是key-value,key 避免重复 url: "{controller}/{action}/{id}",//正则规则:两个斜线 3个变量 defaults: new { controller = "home", action = "index", id = urlparameter.optional } //默认值 没有id变量 就是urlparameter.optional 没有action就是index 没有controller是home ); } }
有关路由,请参考https://www.tuicool.com/articles/ne2qfe
ioc和mvc的结合,工厂的创建和bussiness初始化
mvc请求进来,漏油匹配,找到控制器和action,控制器是个普通的类,action是个普通的实例方法,是不是有一个过程,叫实例化控制器?但是现在希望通过容器来实例化这个控制器。
路由匹配后得到控制器名称--mvchandler---controllerbuilder.getcontrollerfactory()---然后创建控制器的实例。
public class difactory { public static iunitycontainer getcontainer() { iunitycontainer container = null; //container.registertype execonfigurationfilemap filemap = new execonfigurationfilemap(); filemap.execonfigfilename = path.combine(appdomain.currentdomain.basedirectory + "cfgfiles\\unity.config"); configuration configuration = configurationmanager.openmappedexeconfiguration(filemap, configurationuserlevel.none); unityconfigurationsection section = (unityconfigurationsection)configuration.getsection(unityconfigurationsection.sectionname); container = new unitycontainer(); section.configure(container, "bingle"); return container; } }
不要每次都创建一个,判断是否为null
/// <summary> /// 依赖注入工厂 /// </summary> public class difactory { private static object _synchelper = new object(); private static dictionary<string, iunitycontainer> _unitycontainerdictionary = new dictionary<string, iunitycontainer>(); /// <summary> /// 根据containername获取指定的container /// </summary> /// <param name="containername">配置的containername,默认为defaultcontainer</param> /// <returns></returns> public static iunitycontainer getcontainer(string containername) { if (!_unitycontainerdictionary.containskey(containername)) { lock (_synchelper) { if (!_unitycontainerdictionary.containskey(containername)) { //配置unitycontainer iunitycontainer container = new unitycontainer(); execonfigurationfilemap filemap = new execonfigurationfilemap(); filemap.execonfigfilename = path.combine(appdomain.currentdomain.basedirectory + "cfgfiles\\unity.config"); configuration configuration = configurationmanager.openmappedexeconfiguration(filemap, configurationuserlevel.none); unityconfigurationsection configsection = (unityconfigurationsection)configuration.getsection(unityconfigurationsection.sectionname); configsection.configure(container, containername); _unitycontainerdictionary.add(containername, container); } } } return _unitycontainerdictionary[containername]; } }
controllerbuilder有个setcontrollerfactory。
public class binglecontrollerfactory : defaultcontrollerfactory { private logger logger = new logger(typeof(binglecontrollerfactory)); protected override icontroller getcontrollerinstance(requestcontext requestcontext, type controllertype) { this.logger.warn($"{controllertype.name}被构造..."); iunitycontainer container = difactory.getcontainer(); //return base.getcontrollerinstance(requestcontext, controllertype); return (icontroller)container.resolve(controllertype); } }
/// <summary> /// 自定义的控制器实例化工厂 /// </summary> public class unitycontrollerfactory : defaultcontrollerfactory { private iunitycontainer unitycontainer { get { return difactory.getcontainer(); } } /// <summary> /// 创建控制器对象 /// </summary> /// <param name="requestcontext"></param> /// <param name="controllertype"></param> /// <returns></returns> protected override icontroller getcontrollerinstance(requestcontext requestcontext, type controllertype) { if (null == controllertype) { return null; } icontroller controller = (icontroller)this.unitycontainer.resolve(controllertype); return controller; } /// <summary> /// 释放 /// </summary> /// <param name="controller"></param> public override void releasecontroller(icontroller controller) { //释放对象 //this.unitycontainer.teardown(controller);//释放对象 unity容器释放对象只有单例那些,瞬时的是不存在释放管理的,直接.net框架自身会即时完成对象释放 /* i wrote an article about using object lifetimes managers in unity and their impact on disposing. if you use default transientlifetimemanager or perresolvelifetimemanager the unity will even don't track existence of your objects so it can't call dispose. the only lifetime managers which calls dispose on resolved instances are containercontrolledlifetimemanager (aka singleton) and hierarchicallifetimemanager. the dispose is called when the lifetime manager is disposed. */ base.releasecontroller(controller);// } }
步骤:
1、自己定义一个类,继承defaultcontrollerfactory
2、setfactory,实例化控制器会进到这里
3、引入第三方容器,将控制器的实例化换成容器操作
这样就完成了mvc+ioc的结合。