Net學習日記_ASP.Net_MVC_路由

路由映射後調用方法時爲方法同名參數傳值css

 

mvc查找控制器類html

 

在BundleConfige裏面能夠手動合併js文件和css文件,用於瀏覽器加載過程當中,一次性加載。jquery

            //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裏面從新約束mvc

 

區域註冊類裏的AreaName屬性用處asp.net

 

 

 

當服務器在瀏覽文件夾下,查找相應的文件,但咱們能夠自Global.asax.cs裏面約束,指定查找某類玩文件ide

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 完成
*/
相關文章
相關標籤/搜索