ASP.NET MVC5 学习笔记-1 控制器、路由、返回类型、选择器、过滤器

 

[TOC]

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
标签: ASP.NET MVC

MVC5控制器、路由、返回类型、选择器、过滤器的更多相关文章

  1. MVC控制器方法返回类型

    控制器公开控制器操作.操作是控制器上的方法,在浏览器的地址栏中输入特定 URL 时被调用.例如,假设要请求下面的 URL: http://localhost/Product/Index/3 在这种情况 ...

  2. MVC控制器常用方法返回类型

    控制器的常用方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using ...

  3. ASP.NET MVC5 学习笔记-1 控制器、路由、返回类型、选择器、过滤器

    [TOC] 1. Action 1.1 新建项目 新建项目->Web->Asp.net Web应用程序,选择MVC,选择添加测试. 在解决方案上右键,选择"管理NuGet程序包& ...

  4. ASP.NET Core WebAPI控制器返回类型的最佳选项

    前言 从.NET Core 2.1版开始,到目前为止,控制器操作可以返回三种类型的WebApi响应.这三种类型都有自己的优点和缺点,但都缺乏满足REST和高可测性的选项. ASP.NET Core中可 ...

  5. Web API 方法的返回类型、格式器、过滤器

    一.Action方法的返回类型 a) 操作方法的返回类型有四种:void.简单或复杂类型.HttpResponseMessage类型.IHttpActionResult类型. b) 如果返回类型为vo ...

  6. 找到多个与名为“xxx”的控制器匹配的类型。如果为此请求(“{controller}/{action}/{id}”)提供服务的路由没有指定命名空间以搜索与此请求相匹配的控制器,则会发生这种情况。

    一次在建MVC 项目的进行开发的时候,因为后来想到了一个更好的项目名称,就把 Web项目的名称重命名 改了, 然后 程序集名称,默认命名空间,都改成新的了,刚建立的项目本身也不大,运行起来,总是报 & ...

  7. mvc5中重命名项目的名称后,出现"找到多个与名为“Home”的控制器匹配的类型"

    1.已把项目中所有的Webapplication1改为了MvcMovie,但是运行后,还是报错: 找到多个与名为“Home”的控制器匹配的类型 2.已重新生成解决方安,还是不行. 解决方法:把bin文 ...

  8. Spring 框架控制器类方法可用的参数与返回类型

    参数类型 Spring 有内建的 HTTP 消息转换器用于部分简单类型之间的转换 标准 Servlet 类型:HttpServletRequest, HttpServletResponse, Http ...

  9. MVC Action 返回类型

    https://www.cnblogs.com/xielong/p/5940535.html https://blog.csdn.net/WuLex/article/details/79008515 ...

随机推荐

  1. [原创].NET 业务框架开发实战之八 业务层Mapping的选择策略

    原文:[原创].NET 业务框架开发实战之八 业务层Mapping的选择策略 .NET 业务框架开发实战之八 业务层Mapping的选择策略 前言:在上一篇文章中提到了mapping,感觉很像在重新实 ...

  2. 使用autoconf和automake生成Makefile文件(转)

    Makefile好难写 曾经也总结了一篇关于Makefile的文章<make和makefile的简单学习>.但是,总结完以后,发现写Makefile真的是一件非常痛苦的事情,的确非常痛苦. ...

  3. C#使用xpath找到一个节点

    Xpath这是非常强大.但对比是一个更复杂的技术,希望上面去博客园特别想看看一些专业职位.下面是一些简单Xpath的语法和示例,给你参考 <?xml version="1.0" ...

  4. Quartz.net开源作业调度

    Quartz.net开源作业调度框架使用详解 前言 quartz.net作业调度框架是伟大组织OpenSymphony开发的quartz scheduler项目的.net延伸移植版本.支持 cron- ...

  5. 设计模式--简单工厂VS工厂VS抽象工厂

    前几天我一直在准备大学毕业生,始终绑起来,如今,终于有时间去学习设计模式.我们研究今天的话题是植物三口之家的设计模式的控制--简单工厂VS工厂VS抽象工厂. 经过细心推敲,我们不难得出:工厂模式是简单 ...

  6. How to Use NSLog to Debug CGRect and CGPoint

    转载:  http://iosdevelopertips.com/debugging/how-to-use-nslog-to-debug-cgrect-and-cgpoint.html CGPoint ...

  7. dom 规划(html和xml)

    html dom与xml dom关联: 什么是 DOM? DOM 是 W3C(万维网联盟)的标准. DOM 定义了訪问 HTML 和 XML 文档的标准: "W3C 文档对象模型 (DOM) ...

  8. Linux NetHogs监控工具介绍(转)

    NetHogs介绍 NetHogs是一款开源.免费的,终端下的网络流量监控工具,它可监控Linux的进程或应用程序的网络流量.NetHogs只能实时监控进程的网络带宽占用情况.NetHogs支持IPv ...

  9. 如何生成可变表头的excel(转)

    1.实现功能: 传入一个表头和数据,将数据导入到excel中. 为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成.另外为了便于 ...

  10. 二叉搜索树(Binary Search Tree)--C语言描述(转)

    图解二叉搜索树概念 二叉树呢,其实就是链表的一个二维形式,而二叉搜索树,就是一种特殊的二叉树,这种二叉树有个特点:对任意节点而言,左孩子(当然了,存在的话)的值总是小于本身,而右孩子(存在的话)的值总 ...