1. Action

1.1 新建项目

新建项目->Web->Asp.net Web应用程序,选择MVC,选择添加测试。

在解决方案上右键,选择"管理NuGet程序包",在更新页更新全部程序包。

1.2 控制器

控制器在Controllers文件夹内,命名规则是"名称+Controller"


2. 路由

2.1 路由规则

{controller}/{action}/{id}

其中{id}是可选的。

2.2 路由定义RouteConfig.cs

public class RouteConfig
{
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 }
);
}
}

我们自定义一个路由:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
name: "Serial Number",
url: "serial/{lettercase}",
defaults: new { controller = "Home", action = "Serial", lettercase="upper" }
); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

它定义了一个路由,路由名称为"Serial Number", url以"serial"开头,含有一个lettercase参数,使用HomeController.Serial来处理,lettercase默认值为"upper".

现在在HomeController.cs中定义:

public ActionResult Serial(string lettercase)
{
var serial = "ASP.NET mvc5";
if (lettercase == "lower")
{
serial = serial.ToLower();
}
return Content(serial);
}

此时访问:http://localhost:17681/serial/ 或者 http://localhost:17681/serial/lower 都可以。

如果路由中没有包含{lettercase},则可以使用querystring方式传递lettercase: http://localhost:17681/serial/?lettercase=lower:

routes.MapRoute(
name: "Serial Number",
url: "serial",
defaults: new { controller = "Home", action = "Serial" }
);

vs快捷键:F5运行调试; ctrl+F5:运行但不调试,此时运行时可以修改代码;ctrl+shift+b:编译代码,可以在运行时重新加载而无需重启。

3 返回类型

内建Action Result类型:

  • ViewResult:渲染返回完整的网页
  • PartialViewResult:渲染返回网页的一部分,用于Ajax比较多;
  • ContentResult: 返回用户自定义的内容(text,xml)等;
  • JsonResult: 返回Json类型
  • RedirectToRouteResult:重定向

3.1 PartialViewResult的例子

public ActionResult Index()
{
return PartialView();
}

3.2 JsonResult的例子

public ActionResult Serial(string lettercase)
{
var serial = "ASP.NET mvc5";
if (lettercase == "lower")
{
serial = serial.ToLower();
}
//return Content(serial);
return Json(new {name = "serial", value = serial}, JsonRequestBehavior.AllowGet);
}

3.3 RedirectToRouteResult的例子

public ActionResult Serial(string lettercase)
{
var serial = "ASP.NET mvc5";
if (lettercase == "lower")
{
serial = serial.ToLower();
}
return RedirectToAction("Index");
}

4 Action Selector

4.1 HttpPost

public ActionResult Contact()
{
ViewBag.TheMessage = "有问题的话请留言哦~"; return View();
} [HttpPost]
public ActionResult Contact(string message)
{
ViewBag.TheMessage = "感谢你的留言~"; return View();
}

对应的视图

<form method="POST">
<input type="text" name="message"/>
<input type="submit"/>
</form>

4.1.1 防止CSRF,使用ValidateAntiForgeryToken

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
} return View(movie);
}

对应的视图使用@Html.AntiForgeryToken

@using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Movie</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>

4.1.2 验证Post请求 ModelState.IsValid

使用ModelState.IsValid来验证发送来的模型是否正常。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
db.Entry(movie).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}

4.2 ActionName

[ActionName("about-the-site")]
public ActionResult About()
{
ViewBag.Message = "Your application description page."; return View("About");
}

此时访问地址就是http://localhost:17681/Home/about-the-site

4.3 Route

[Route("home/create")]
public ActionResult Create()
{ }

5. 过滤器

常见的过滤器

5.1 Authorize属性

[Authorize(Roles="administrator", Users="liulx")]
[HttpPost]
public ActionResult Create(Customer customer)
{
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}

Authorize可以不带参数,修饰class,如果class是Authorize修饰的,那么可以用[AllowAnonymous]修饰对应的方法允许匿名访问。

5.2 Action filter

创建自定义的Action Filter:

  • 继承ActionFilterAttribute
  • 重写OnActionExecuting方法,该方法在Action之前执行
  • 重写OnActionExecuted方法,该方法在Action之后执行
public class MyLoggingFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Logger.logRequest(request.UserHostAddress);
base.OnActionExecuted(filterContext);
}
}

调用

[MyLoggingFilter]
public ActionResult Index()
{
// throw new StackOverflowException();
return View();
}

要想在全局应用自定义的Filter,可以这样:

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//添加自定义Filter
filters.Add(new MyLoggingFilterAttribute());
filters.Add(new HandleErrorAttribute());
}
}

5.3 Result Filter

[OutputCache(Duration=1800)]
public ActionResult Index()
{
// throw new StackOverflowException();
return View();
} [OutputCache(Duration=1800, VaryByParam="id")]
public ActionResult Details(int id)
{
Product p = db.Products.Find(id);
return View(p);
}

5.4 Exception Filter

[HandleError(View="MyError")]
public ActionResult Index()
{
// throw new StackOverflowException();
return View();
} [HandleError(View="MyError2", ExceptionType=typeof(DivideByZeroException))]
public ActionResult Details(int id)
{
Product p = db.Products.Find(id);
return View(p);
}

ASP.NET MVC5 学习笔记-1 控制器、路由、返回类型、选择器、过滤器的更多相关文章

  1. ASP.NET MVC5学习笔记01

    由于之前在项目中也使用MVC进行开发,但是具体是那个版本就不是很清楚了,但是我觉得大体的思想是相同的,只是版本高的在版本低的基础上增加了一些更加方便操作的东西.下面是我学习ASP.NET MVC5高级 ...

  2. ASP.NET MVC5学习笔记之Controller同步执行架构分析

    在开始之前,声明一下,由于ASP.NET MVC5正式发布了,后面的分析将基于ASP.NET MVC5最新的源代码.在前面的内容我们分析了怎样根据路由信息来确定Controller的类型,并最终生成C ...

  3. ASP.NET MVC5学习笔记之Filter提供体系

    前面我们介绍了Filter的基本使用,但各种Filter要在合适的时机运行起来,需要预先准备好,现在看看ASP.NET MVC框架是怎么做的. 一.Filter集合 在ControlerActionI ...

  4. ASP.NET MVC5 学习笔记-2 Razor

    1. Razor @*注释*@ 你在用 @Request.Browser.Browser, 发送邮件给support@qq.com, 转义@@qq @{ var amounts = new List& ...

  5. Asp.net MVC5 学习笔记

    控制器(controller)主要负责响应用户的输入,并且在响应时修改模型(Model).通过这种方式,MVC模式中的控制器主要关注的是应用程序流.输入数据的处理,以及对相关视图(View)输出数据的 ...

  6. ASP.NET MVC5学习笔记之Action参数模型绑定之模型元数据和元数据提供

    一. 元数据描述类型ModelMetadata 模型元数据是对Model的描述信息,在ASP.NET MVC框架中有非常重要的作用,在模型绑定,模型验证,模型呈现等许多地方都有它的身影.描述Model ...

  7. ASP.NET MVC5学习笔记之Filter基本介绍

    Filter是ASP.NET MVC框架提供的基于AOP(面向方面)设计,提供在Action执行前后做一些非业务逻辑通用处理,如用户验证,缓存等.现在来看看Filter相关的一些类型信息. 一.基本类 ...

  8. ASP.NET MVC5学习笔记之Controller执行ControllerDescriptor和ActionDescriptor

    一. ControllerDescriptor说明 ControllerDescriptor是一个抽象类,它定义的接口代码如下: public abstract class ControllerDes ...

  9. ASP.NET MVC5 学习笔记-3 Model

    1. Model 1.1 添加一个模型 注意,添加属性时可以输入"prop",会自动输入代码段. public class CheckoutAccount { public int ...

随机推荐

  1. [置顶] fmt日期格式化

    jstl中的日期格式化 <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> & ...

  2. MyMVC框架的使用

    1)在web.config 中system.web 节点下加入例如以下代码 <pages controlRenderingCompatibilityVersion="4.0" ...

  3. linux线程之pthread_join和pthread_detach

    在任何一个时间点上,线程是可结合的(joinable)或者是分离的(detached).一个可结合的线程能够被其他线程收回其资源和杀死.在 被其他线程回收之前,它的存储器资源(例如栈)是不释放的.相反 ...

  4. 关于js封装框架类库之选择器引擎(一)

    选择器模块之传统做法 var tag = function (tag){ return document.getElementsByTagName(tag); } var id = function ...

  5. 文件上传下载样式 --- bootstrap

    在平时工作中,文件上传下载功能属于不可或缺的一部分.bootstrap前端样式框架也使用的比较多,现在根据bootstrap强大的样式模板,自定义一种文件下载的样式. 后续会使用spring MVC框 ...

  6. Uploadif稍做扩展使用

    文章出自Uploadify扩展配置使用http://www.wuyinweb.com/doc/52/57.aspx 在做项目中涉及多文件上传,经过筛选,选择了Uploaidify,但还涉及一个问题,就 ...

  7. CodeForces 452C Magic Trick (排列组合)

    #include <iostream> #include <cstdio> #include<cmath> #include<algorithm> us ...

  8. iOS 纯代码适配iPhone6,6+

    链接地址:http://blog.csdn.net/codywangziham01/article/details/37658399 转自:http://www.maxiaoguo.com/cloth ...

  9. php实现简单的上一页下一页

    思路整理: 现在好多人用id的增1和减1实现上一篇和下一篇但是难道文章ID不会断了吗所以你要知道上个ID和个ID是多少就OK了那怎么解决这个问题呢,很简单例子:假如这篇文章的ID200 <a h ...

  10. javascript Error对象详解

    今天谈一下在IE浏览器下返回执行错误的Javascript代码所在的问题.其中在IE浏览器下,如果你使用了try-catch,那么当出现异常的时候,IE浏览器会传递一个Error对象. ~~~怎么通过 ...