ASP.NET MVC必知必会知识点总结(一)

时间:2023-03-09 20:40:22
ASP.NET MVC必知必会知识点总结(一)

一、URL Routing

1.添加URL路由映射的一般方法(在RegisterRoutes方法中添加):

//第一种(建议采用这种):
routes.MapRoute(
"MyRoute", // 路由名称
"{controller}/{action}/{id}",// 带有参数的 URL
new { controller = "Default", action = "Index", id = UrlParameter.Optional }, // 参数默认值
new { controller=@"\w+",action=@"^Get|Update|Delete\w+$",id=@"\d+" } //路由约束
); //第二种:
Route myRoute = new Route("{controller}/{action}/{id}", // 带有参数的 URL
new RouteValueDictionary(new { controller = "Default", action = "Index", id = UrlParameter.Optional }), // 参数默认值
new RouteValueDictionary(new { controller = @"\w+", action = @"^Get|Update|Delete\w+$", id = @"\d+" }), //路由约束
new MvcRouteHandler());
routes.Add("MyRoute", myRoute);

2.自定义路由约束:通过实现 IRouteConstraint 接口来定义自己的路由约束规则

    /// <summary>
/// 访问时间约束(当大于指定的时间才允许访问)
/// </summary>
public class AccessTimeConstraint : IRouteConstraint
{
DateTime? allowAccessTime = null; public AccessTimeConstraint(DateTime allowAccessTime)
{
this.allowAccessTime = allowAccessTime;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return allowAccessTime == null ? true : ((DateTime)allowAccessTime).CompareTo(DateTime.Now) <= 0;
}
} routes.MapRoute("default", "test/{action}/{id}",
new { controller = "Default", action = "Index", id = UrlParameter.Optional },
new{accessTimeConstraint=new AccessTimeConstraint(DateTime.Parse("2015-08-28 10:00:00"))});

3.Area注册的路由与Global注册的路由发生冲突解决方案:为Global注册的路由指定命名空间,路由系统在对路由进行匹配时,优先匹配指定了命名空间的controller,如果匹配到则即刻停止查找,如果在指定的命名空间下没有匹配到对应的controller,再按照一般的方式进行匹配。

public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
} public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication1.Controllers" }
);
}

4.在 Controller 中从上下文对象中可以获取如下的状态数据:

ASP.NET MVC必知必会知识点总结(一)

5.Controller的基本工作顺序(有视图的情况):

-->IController.Execute-->Controller.CreateActionInvoker

-->IActionInvoker.InvokeAction-->ActionResult.ExecuteResult

-->ViewResultBase.FindView-->IVew.Render-->IViewEngine.ReleaseView

6.若要自定义Controller,只要实现IController接口并重写Execute方法即可,若要自定义ActionResult,只要继承ActionResult抽象类并重写ExecuteResult方法即可,若要自定义视图引擎,则需要继承ViewResultBase抽象类并重写FindView方法、实现IVew接口并重写Render方法,以及实现IViewEngine接口并重写ReleaseView方法

7.从 Action 传递数据到 View 的方式:

ViewBag:是动态(dynamic)的弱类型,在程序运行的时候解析,是 MVC3 中新增的特性,只在当前View有效。
ViewData:是字典集合,只在当前View有效,性能比 ViewBag 高,但是使用的时候需要类型转换。
TempData:是字典集合,一般用于两个请求之间临时缓存内容或页面间传递消息,保存在 Session 中,使用完以后则从 Session 中被清除。