• SSH.net之主程序


    现在开始进行mvc3.0主程序的编码

    一、首先引入Service,Model项目。在HomeController.cs中

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.Mvc;
     6 using Service;
     7 using Model;
     8 namespace Nssh.project.Controllers
     9 {
    10     public class HomeController : Controller
    11     {
    12         public IUserService UsersService { get; set; }
    13 
    14         public IRolesService RolesService { get; set; }
    15 
    16         public IPermissionService PermissionService { get; set; }
    17 
    18         public ActionResult Index()
    19         {
    20             ViewData["Message"] = "Welcome to ASP.NET MVC!";
    21 
    22             Users u = UsersService.Get(1);
    23             if (null != u)
    24             {
    25                 ViewData["uname"] = u.uname;
    26             }
    27             else {
    28                 ViewData["uname"] = "no one";
    29             }
    30             return View();
    31         }
    32 
    33 
    34     }
    35 }

    二、添加Controller工厂,引入项目根目录下lib文件夹下文件(后面会有上传,其中包括spring,nhibernate,log4net,还有nunit测试dll文件):

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.Mvc;
     6 using Spring.Context.Support;
     7 using Spring.Context;
     8 using System.Web.SessionState;
     9 
    10 namespace Nssh.project.Controllers
    11 {
    12     /// <summary>
    13     /// Spring.NET ControllerFacotry
    14     /// </summary>
    15     public class SpringControllerFactory : IControllerFactory
    16     {
    17         /// <summary>
    18         /// Default ControllerFactory
    19         /// </summary>
    20         private static DefaultControllerFactory defalutfactory = null;
    21         //重写Ctroller生成器
    22         public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
    23         {
    24             //WebApplicationContext需要引入文件:spring.web.dll
    25             WebApplicationContext ctx = ContextRegistry.GetContext() as WebApplicationContext;
    26             string controller = controllerName + "Controller";
    27             //查找在Controller.xml里是否配置该Controller,如果配置过,则生成配置类型的Controoler对象。(主要是生成已经配置了的Controller对象里面的属性对象:<property name="AddressManager" ref="AddressManager"/>)
    28             if (ctx.ContainsObject(controller))
    29             {
    30                 //如果配置,则取出。(生成注入属性的对象)
    31                 object controllerf = ctx.GetObject(controller);
    32                 return (IController)controllerf;
    33 
    34             }
    35             else
    36             {
    37                 //实例化普通Controller对象生成器
    38                 if (defalutfactory == null)
    39                 {
    40                     defalutfactory = new DefaultControllerFactory();
    41                 }
    42 
    43                 return defalutfactory.CreateController(requestContext, controllerName);//使用系统默认的方式生成Contraller对象
    44 
    45             }
    46         }
    47 
    48         //释放系统默认Controller生成器生成的Controller对象
    49         public void ReleaseController(IController controller)
    50         {
    51             //get spring context
    52             IApplicationContext ctx = ContextRegistry.GetContext();
    53             if (!ctx.ContainsObject(controller.GetType().Name))
    54             {
    55                 if (defalutfactory == null)
    56                 {
    57                     defalutfactory = new DefaultControllerFactory();
    58                 }
    59 
    60                 defalutfactory.ReleaseController(controller);
    61             }
    62         }
    63 
    64 
    65 
    66         public SessionStateBehavior GetControllerSessionBehavior(System.Web.Routing.RequestContext requestContext, string controllerName)
    67         {
    68             return SessionStateBehavior.Default;
    69         }
    70     }
    71 }

    三、设置controllers.xml属性

     1 <?xml version="1.0" encoding="utf-8" ?>
     2 <objects xmlns="http://www.springframework.net">
     3 
     4 
     5     <object id="HomeController" type="Nssh.project.Controllers.HomeController, Nssh.project" singleton="false">
     6         <property name="UsersService" ref="UsersService"/>
     7         <!--注入Service类,当转入HomeController时,生成RolesService对象(该对象添加了事物代理)-->
     8         <property name="RolesService" ref="RolesService"/>
     9         <property name="PermissionService" ref="PermissionService"/>
    10     </object>
    11 
    12 </objects>

    设置xml文件属性:

    四、在global文件中注册:

    1 protected void Application_Start()
    2         {
    3             log4net.Config.XmlConfigurator.Configure();
    4             ControllerBuilder.Current.SetControllerFactory(typeof(Controllers.SpringControllerFactory));
    5 
    6             AreaRegistration.RegisterAllAreas();
    7             RegisterGlobalFilters(GlobalFilters.Filters);
    8             RegisterRoutes(RouteTable.Routes);
    9         }

    五、配置web.config文件

      1 <?xml version="1.0" encoding="utf-8"?>
      2 <!--
      3   有关如何配置 ASP.NET 应用程序的详细信息,请访问
      4   http://go.microsoft.com/fwlink/?LinkId=152368
      5   -->
      6 
      7 <configuration>
      8     <!--!!!!!!!!!!!!!-->
      9     <configSections>
     10         <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
     11 
     12         <sectionGroup name="common">
     13             <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
     14         </sectionGroup>
     15         <sectionGroup name="spring">
     16             <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web" />
     17             <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
     18             <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core" />
     19         </sectionGroup>
     20 
     21         <section name="databaseSettings" type="System.Configuration.NameValueSectionHandler"/>
     22     </configSections>
     23 
     24     <!--日志通过邮件发送:http://www.cnblogs.com/kissdodog/archive/2013/04/30/3051821.html -->
     25     <!--http://www.cnblogs.com/agtaimaer/archive/2008/11/15/log4net.html-->
     26     <log4net debug="true">
     27         <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
     28             <!--appender的file指定了log存储文件的路径,如果该路径不存在会自动创建;-->
     29             <param name="File" value="LogsApplication.log.txt" />
     30             <!--文件名称-->
     31             <param name="datePattern" value="MM-dd HH:mm" />
     32             <!--appenderToFile:标识是添加到现有文件中还是覆盖原有的日志,true表示添加到已经存在的日志文件,如果该文件大小已经超过最大,则新建一个空白日志文件-->
     33             <param name="AppendToFile" value="true" />
     34             <!--设置无限备份=-1 ,最大备份数为1000-->
     35             <param name="maxSizeRollBackups" value="1000" />
     36             <!--每个文件的最大:1024k-->
     37             <param name="maximumFileSize" value="1024" />
     38             <!--名称是否可以更改为false为可以更改-->
     39             <param name="StaticLogFileName" value="false" />
     40 
     41             <!--layout:设定日志的输出格式,各个参数所代表的意思,格式太多,具体可参照官方文档:http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html-->
     42             <!--几个主要的说明如下;
     43             %m:message,
     44             %d: date,记录log的时间,
     45             %n:new line,
     46             %c:class 当前日志对象的名字
     47             %L:语句所在行号
     48             %F:语句所在文件名
     49                %m[%message]       : 输出的日志消息
     50                %n                 : 换行
     51                %d[%datetime]      : 输出当前语句运行的时刻
     52                %r                 : 输出程序从运行到执行到当前语句时消耗的毫秒数
     53                %d                 : 当前语句所在的线程ID
     54                %p                 : 日志的当前优先级别
     55                %c                 :当前日志对象的名称
     56                %L                 : 输出语句所在的行号
     57                %F                 :输出语句所在的文件名
     58                %-数字              :表示该项的最小长度,如果不够,则用空格填充
     59             -->
     60             <layout type="log4net.Layout.PatternLayout">
     61                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
     62             </layout>
     63             <!--MaximumFileSize:文件的最大值,可以使KB或MB为单位,与MaxFileSize等价,唯一不一样的是MaxFileSize 可以使用bytes来设值;-->
     64             <!--MaxSizeRollBackups:设置变换文件大小的文件值即,当文件超过设定值时,则新建文件;-->
     65             <!--DatePattern :指定生成文件的格式-->
     66         </appender>
     67         <!--<appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender">
     68             <layout type="log4net.Layout.PatternLayout">
     69                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
     70             </layout>
     71         </appender>
     72         <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
     73             <layout type="log4net.Layout.PatternLayout">
     74                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
     75             </layout>
     76         </appender>
     77         <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
     78             <param name="File" value="Logs/Log.txt" />
     79             <param name="AppendToFile" value="true" />
     80             <param name="MaxSizeRollBackups" value="10" />
     81             <param name="MaximumFileSize" value="100K" />
     82             <param name="RollingStyle" value="Size" />
     83             <param name="StaticLogFileName" value="true" />
     84             <layout type="log4net.Layout.PatternLayout">
     85                 <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
     86             </layout>
     87         </appender>-->
     88         <root>
     89             <!--设置日志输出级别-->
     90             <level value="Warn" />
     91             <!--设置日志输出类型-->
     92             <appender-ref ref="LogFileAppender" />
     93         </root>
     94     </log4net>
     95     <spring>
     96         <parsers>
     97             <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data" />
     98             <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data" />
     99         </parsers>
    100         <context>
    101             <resource uri="config://spring/objects" />
    102             <resource uri="assembly://DAO/DAO/Repository.xml" />
    103             <resource uri="assembly://Service/Service/Service.xml" />
    104             <resource uri="assembly://Nssh.project/Nssh.project.Controllers/Controllers.xml"/>
    105         </context>
    106         <objects xmlns="http://www.springframework.net" />
    107     </spring>
    108 
    109     <!--数据库连接字符串-->
    110     <databaseSettings>
    111         <add key="db.datasource" value="LIPPOR-PCLIPPOR"/>
    112         <add key="db.user" value="sa"/>
    113         <add key="db.password" value="123"/>
    114         <add key="db.database" value="nssh"/>
    115     </databaseSettings>
    116 
    117     <!--很重要-->
    118     <!--<appSettings>
    119         <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="NHibernateSessionFactory" />
    120     </appSettings>-->
    121 
    122 
    123     <connectionStrings />
    124     <!--!!!!!!!!!!!!!-->
    125     
    126 
    127   <appSettings>
    128     <add key="webpages:Version" value="1.0.0.0" />
    129     <add key="ClientValidationEnabled" value="true" />
    130     <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    131       <!--!!!!!!!!!!!!!-->
    132       <add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="NHibernateSessionFactory" />
    133 
    134       <!--!!!!!!!!!!!!!-->
    135   </appSettings>
    136 
    137   <system.web>
    138       <!--!!!!!!!!!!!!!-->
    139       <httpModules>
    140           <!--很重要-->
    141           <add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate21"/>
    142           <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" />
    143       </httpModules>
    144       <!--!!!!!!!!!!!!!-->
    145       
    146       
    147     <compilation debug="true" targetFramework="4.0">
    148       <assemblies>
    149         <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    150         <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    151         <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    152         <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    153         <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    154       </assemblies>
    155     </compilation>
    156 
    157     <authentication mode="Windows" />
    158 
    159     <authorization>
    160       <deny users="?" />
    161     </authorization>
    162 
    163 
    164 
    165     <pages>
    166       <namespaces>
    167         <add namespace="System.Web.Helpers" />
    168         <add namespace="System.Web.Mvc" />
    169         <add namespace="System.Web.Mvc.Ajax" />
    170         <add namespace="System.Web.Mvc.Html" />
    171         <add namespace="System.Web.Routing" />
    172         <add namespace="System.Web.WebPages"/>
    173       </namespaces>
    174     </pages>
    175   </system.web>
    176 
    177   <system.webServer>
    178     <validation validateIntegratedModeConfiguration="false"/>
    179     <modules runAllManagedModulesForAllRequests="true"/>
    180   </system.webServer>
    181 
    182   <runtime>
    183     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    184       <dependentAssembly>
    185         <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    186         <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
    187       </dependentAssembly>
    188     </assemblyBinding>
    189   </runtime>
    190 </configuration>

     自动生成的web.config文件中有配置profile,roleManager。由于用不到,而且会使程序报错,所以删掉两个节点

    到现在基本完成,编码view页面

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        主页
    </asp:Content>
    
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <h2><%=ViewData["uname"].ToString() %></h2>
        <p>
            若要了解有关 ASP.NET MVC 的更多信息,请访问 <a href="http://asp.net/mvc" title="ASP.NET MVC 网站">http://asp.net/mvc</a></p>
    </asp:Content>

    运行程序:

    显示no one,因为我们程序里还没有数据。后面我们会添加数据。

    但是,运行时弹出一个小错误:

    解决方法很简单,找一个小图标命名为:favicon.ico,放到项目Nssh.project根目录下,完美解决了

    源码下载地址:源码

  • 相关阅读:
    Shelve Instance 操作详解
    Rebuild Instance 操作详解
    Snapshot Instance 操作详解
    Nova Suspend/Rescue 操作详解
    Pause/Resume Instance 操作详解
    Terminate Instance 操作详解
    Nova reboot 和 lock 操作
    Start Instance 操作详解
    tar --help
    VIM标记 mark 详解
  • 原文地址:https://www.cnblogs.com/lippor/p/4139737.html
Copyright © 2020-2023  润新知