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. Matlab学习------------带有右键菜单的GUI学习实例

    实例步骤: 须要设置UIContextMenu,否则点击右键不显示. 右键点击第一个菜单之后:(在菜单中加入对应的回调函数) function r1_Callback(hObject, eventda ...

  2. C# 使用WinRar命令压缩和解压缩

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  3. uva10954 - Add All(multiset功能)

    题目:10954 - Add All 题目大意:求n个数的和,可是有点不一样的是题目要求计算最少花费.每次两个数相加,得到的那个数就是每次计算的cost. 解题思路:之前没有想到用multiset,自 ...

  4. [Network]Transport Layer

    1 Principles behind Transport Layer Services 1.1 Multiplexing/Demultiplexing Multiplexing at sender ...

  5. R0-R37它是Arm 寄存器,那是,CPU内部。和GPIO注册所有外设。换句话说,要是arm的cpu,它包含了其他芯片公司将有R0-R37,和GPIO寄存器只有一个特定的芯片。

    R0-R37它是Arm 寄存器.那是,CPU内部.和GPIO注册所有外设. 换句话说,要是arm的cpu,它包含了其他芯片公司将有R0-R37,和GPIO有. 版权声明:本文博主原创文章.博客,未经同 ...

  6. C++ - 派生类访问模板基类(templatized base class)命名

    派生类访问模板基类(templatized base class)命名 本文地址: http://blog.csdn.net/caroline_wendy/article/details/239936 ...

  7. Mongodb语法总结

    mongodb与mysql指挥控制 由数据库中的一般传统的关系数据库(database).表(table).记录(record)三个层次概念组成.MongoDB是由数据库(database).集合(c ...

  8. Oracle 中用一个表的数据更新另一个表的数据

    Oracle 中用一个表的数据更新另一个表的数据 分类: SQL/PLSQL2012-05-04 15:49 4153人阅读 评论(1) 收藏 举报 oraclemergesubqueryinsert ...

  9. CSS hack方式

    史上最全的CSS hack方式一览   做前端多年,虽然不是经常需要hack,但是我们经常会遇到各浏览器表现不一致的情况.基于此,某些情况我们会极不情愿的使用这个不太友好的方式来达到大家要求的页面表现 ...

  10. .NET应用架构设计—四色原型模式(色彩造型、域无关的模型)(概念版)

    阅读文件夹: 1.背景介绍 2.问自己,UML对你来说有意义吗?它帮助过你对系统进行分析.建模吗? 3.一直以来事实上我们被一个缝隙隔开了,使我们对OOAD遥不可及 4.四色原型模式填补这个历史缝隙, ...