Net学习日记_ASP.Net_MVC_路由

路由映射后调用方法时为方法同名参数传值

 

mvc查找控制器类

 

在BundleConfige里面可以手动合并js文件和css文件,用于浏览器加载过程中,一次性加载。

            //1.用户可以 手动 添加 js绑定对象,取一个 名字(虚拟路径),添加要绑定的JS文件 路径
            bundles.Add(new ScriptBundle("~/jsValid")
                .Include("~/Scripts/jquery-1.7.1.min.js")
                .Include("~/Scripts/jquery.validate.min.js")
                .Include("~/Scripts/jquery.validate.unobtrusive.min.js"));

            //2.合并 css 文件
            bundles.Add(new StyleBundle("~/cssMy").Include("~/content/1.css", "~/content/2.css"));

            //2.用户 开启 js/css 压缩合并功能
            BundleTable.EnableOptimizations = true;

 

 

在RouteConfige里面指定浏览器访问过程,匹配url

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Add", id = UrlParameter.Optional },
                constraints: new {id = @"\d*" }//为{id}占位符 设置约束,必须是 数值
            );

            routes.MapRoute(
                name: "Default2",
                url: "{controller}/{action}/{name}",
                defaults: new { controller = "Home", action = "Add", name = UrlParameter.Optional },
                constraints: new { name = "[a-z]+" }//为{name}占位符 设置约束,必须是 字母
            );

            routes.MapRoute(
                name: "Default3",
                url: "{action}/{controller}/{name}",
                defaults: new { controller = "Home", action = "Add", name = UrlParameter.Optional },
                constraints: new { name = "[a-z]+" }//为{name}占位符 设置约束,必须是 字母
            );

 

 

建立Area区域时,要具有区域约束

namespace P01MVCRoute.Areas.admin
{
    public class adminAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "admin_default",
                "admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 

其中,1.return "admin"不能改,应为返回这个就是AreaName,指向哪个文件夹下寻找;

           2.namespace不易更改,如果更改,则去RouteConfige里面重新约束

 

区域注册类里的AreaName属性用处

 

 

 

当服务器在浏览文件夹下,查找相应的文件,但我们可以自Global.asax.cs里面约束,指定查找某类玩文件

namespace P01MVCRoute
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()//整个mvc网站被访问时,执行这个方法一次
        {
            PureViewEngines();
            //ViewEngines.Engines.RemoveAt(0);
            //ViewEngineCollection vec = ViewEngines.Engines;
            //RazorViewEngine rve = vec[0] as RazorViewEngine;

            //string[] oldPaths = rve.ViewLocationFormats;
            //string[] newPaths = new string[oldPaths.Length + 1];
            //oldPaths.CopyTo(newPaths, 0);
            //newPaths[newPaths.Length - 1] = "~/MyViews/{1}/{0}.cshtml";


            //1.注册区域路由
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            //注册当前网站 路由
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        #region 1.0 保留razor视图引擎,其它的都去掉 -void PureViewEngines()
        /// <summary>
        /// 保留razor视图引擎,其它的都去掉
        /// </summary>
        void PureViewEngines()
        {
            //System.Web.Razor.RazorCodeLanguage.Languages.Remove("vbhtml");

            //移除 集合中 默认添加的 WebFormViewEngine
            ViewEngines.Engines.RemoveAt(0);

            //ViewEngines.Engines.Clear();
            //ViewEngines.Engines.Add(new RazorViewEngine());

            RazorViewEngine razor = ViewEngines.Engines[0] as RazorViewEngine;

            //移除RazorViewEngine中的 vbhtml 路径模版。

            razor.FileExtensions = new string[] { "cshtml" };
            razor.AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" };
            razor.AreaMasterLocationFormats = new string[]{
                 "~/Areas/{2}/Views/{1}/{0}.cshtml",
                 "~/Areas/{2}/Views/Shared/{0}.cshtml"
            };

            razor.AreaPartialViewLocationFormats = new string[]{
                 "~/Areas/{2}/Views/{1}/{0}.cshtml",
                 "~/Areas/{2}/Views/Shared/{0}.cshtml"
            };

            razor.MasterLocationFormats = new string[]{
                 "~/Views/{1}/{0}.cshtml",
                 "~/Views/Shared/{0}.cshtml"
            };

            razor.PartialViewLocationFormats = new string[]{
                 "~/Views/{1}/{0}.cshtml",
                 "~/Views/Shared/{0}.cshtml"
            };

            razor.ViewLocationFormats = new string[]{
                 "~/Views/{1}/{0}.cshtml",
                 "~/Views/Shared/{0}.cshtml"
            };
        }
        #endregion
    }
}

 

 

 

 

 

 

 

 

 

过滤器的调用过程

Action过滤器是控制方法的;而Result过滤器则是控制视图的。

 

过滤器的基本用法

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());

            //3. 添加全局过滤器
            filters.Add(new Filters.MyActionFilterAttribute());

            filters.Add(new Filters.MyHandleErrorAttribute());
        }
    }

 

//[Filters.MyActionFilter]//2.将 过滤器 加到当前类上
    public class HomeController : Controller
    {
        public HomeController()
        {
            System.Web.HttpContext.Current.Response.Write(" HomeController 构造函数<br/> ");
        }

        //[Filters.MyActionFilter]//1.将 过滤器 加到方法上
        //[Filters.Money]
        [Filters.MyResultFilter]
        [Filters.MyAuthorize]
        public ActionResult Index()
        {
            Response.Write("Index 方法<br/>");
            ViewBag.name = "时间:" + DateTime.Now;
            return View();
        }

        public ActionResult GetDate()
        {
            return View();
        }

        //[Filters.MyHandleError]
        public ActionResult GetErr()
        {
            int a = 0;
            int b = 1 / a;
            return View();
        }
    }

 

   /// <summary>
    /// Action方法 过滤器 类
    /// </summary>
    public class MyActionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 在  Action方法之前 调用
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //1. RouteData 中 保存了 当前请求 匹配的 路由信息和路由对象
            //             如果本次请求 是请求了某个 区域 里的 控制器方法,还可以通过filterContext.RouteData.DataTokens["area"]获取区域名

            //string strArea = filterContext.RouteData.DataTokens["area"].ToString();
            string strController = filterContext.RouteData.Values["controller"].ToString();
            string strAction = filterContext.RouteData.Values["action"].ToString();
            //filterContext.RouteData.GetRequiredString

            //2.另一种方式 获取 请求的 类名和方法名
            string strAction2 = filterContext.ActionDescriptor.ActionName;
            string strController2 = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            //2.1检查 被请求方法 是否 加了 MoneyAttribute 特性
            if (filterContext.ActionDescriptor.IsDefined(typeof(Filters.MoneyAttribute), false))
            {
                //直接为 请求 设置 返回结果,而不执行 对应的 Action 方法,也不执行 OnActionExcuted,但是,会执行 Result过滤器和 生成视图
                filterContext.Result = new ContentResult() { Content = "<br/>哈哈哈,直接被跳过了吧~~~!<br/>" };
            }
                     
            filterContext.HttpContext.Response.Write("哇哈哈哈~!OnActionExecuting<br/>");
            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// 在  Action方法之后 调用
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Write("哇哈哈哈~!OnActionExecuted<br/>");
            base.OnActionExecuted(filterContext);
        }
    }
/// <summary>
    /// 授权过滤器 - 在 Action过滤器前 执行
    /// </summary>
    public class MyAuthorizeAttribute:AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Write("<br/>OnAuthorization<br/>");
            //注释掉 父类方法,因为 父类里的 OnAuthorization 方法会 调用 asp.net的授权验证机制!
            //base.OnAuthorization(filterContext);
        }
    }
    /// <summary>
    /// 异常处理 过滤器
    /// </summary>
    public class MyHandleErrorAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            //1.获取异常对象
            Exception ex = filterContext.Exception;
            //2.记录异常日志
            //3.重定向友好页面
            filterContext.Result = new RedirectResult("~/error.html");
            //4.标记异常已经处理完毕
            filterContext.ExceptionHandled = true;

            base.OnException(filterContext);
        }
    }

 

    /// <summary>
    /// Result 过滤器 类 - 如果请求的是 要加载视图的 Action 方法的话
    ///                   在 视图加载 前 后 调用方法
    /// </summary>
    public class MyResultFilterAttribute:System.Web.Mvc.ActionFilterAttribute
    {
        /// <summary>
        /// 加载 "视图" 前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Write("加载 视图 前执行 OnResultExecuting <br/>");
            base.OnResultExecuting(filterContext);
        }

        /// <summary>
        /// 加载"视图" 后执行
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnResultExecuted(System.Web.Mvc.ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Write("加载 视图 后执行 OnResultExecuted <br/>");
            base.OnResultExecuted(filterContext);
        }
    }

还可以在Global里面修改,在11个管道内,执行哪类请求。

namespace P01MVCFilter
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);         
        }

        //public void Application_Error(object sender, EventArgs e)
        //{
        //}

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication obj = sender as HttpApplication;
            obj.Context.Response.Write("1Application_BeginRequest<br/>");
        }

        //public void Application_AuthenticateRequest(object sender, EventArgs e)
        //{
        //    HttpApplication obj = sender as HttpApplication;
        //    obj.Context.Response.Write("2Application_AuthenticateRequest<br/>");
        //}

        //public void Application_PostAuthenticateRequest(object sender, EventArgs e)
        //{
        //    HttpApplication obj = sender as HttpApplication;
        //    obj.Context.Response.Write("3Application_PostAuthenticateRequest<br/>");
        //}

        //public void Application_AunthorizeRequest(object sender, EventArgs e)
        //{
        //    HttpApplication obj = sender as HttpApplication;
        //    obj.Context.Response.Write("4Application_AunthorizeRequest<br/>");
        //}

        //public void Application_PostAuthorizeRequest(object sender, EventArgs e)
        //{
        //    HttpApplication obj = sender as HttpApplication;
        //    obj.Context.Response.Write("5Application_PostAuthorizeRequest<br/>");
        //}


        public void Application_ResolveRequestCache(object sender, EventArgs e)
        {
            HttpApplication obj = sender as HttpApplication;
            obj.Context.Response.Write("6Application_ResolveRequestCache<br/>");
        }

        public void Application_PostResolveRequestCache(object sender, EventArgs e)
        {
            HttpApplication obj = sender as HttpApplication;
            obj.Context.Response.Write("7Application_PostResolveRequestCache<br/>");
        }
        public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication obj = sender as HttpApplication;
            obj.Context.Response.Write("11Application_PreRequestHandlerExecute<br/>");
        }
    }
}

/*
1.BeginRequest  开始处理请求
2.AuthenticateRequest 授权验证请求,获取用户授权信息
3.PostAuthenticateRequest 获取成功
4.AunthorizeRequest 授权,一般来检查用户是否获得权限
5.PostAuthorizeRequest 获得授权
6.ResolveRequestCache 获取页面缓存结果(如果没有则执行)
7.PostResolveRequestCache 已获取缓存
8.PostMapRequestHandler 创建页面对象
9.AcquireRequestState 获取Session -- 先判断当前页面对象是否实现了IRequiresSessionState接口,如果实现了,则从浏览器发来的请求报文头中获得SessionId,并到服务器的 Session池中获得对应的Session对象,最后赋值给 HttpContext的Session属性。
10.PostAcquireRequestState 获得Session
11.PreRequestHandlerExecute 准备执行页面对象
   ×执行页面对象的ProcessRequest方法(1.ashx,1.aspx),如果请求的是1.aspx,则会运行页面生命周期
12.PostRequestHandlerExecute 执行完页面对象了
13.ReleaseRequestState 释放请求状态
14.PostReleaseRequestState 已释放请求状态
15.UpdateReuqestCache 更新缓存
16.PostUpdateRequestCache 已更新缓存
17.LogRequest 日志记录
18.PostLogRequest 已完成日志
19.EndRequest 完成
*/

 

posted @ 2018-01-11 20:18  兽人松  阅读(172)  评论(0编辑  收藏  举报