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. 玩转Web之JavaScript(二)-----javaScript语法总结(二) 涉及Date与数组的语法

    Date: document.write(document.lastModified)  网页最后一次更新时间 a=new Date();  //创建 a 为一个新的时期象 y=a.getY ear( ...

  2. 寒假了,想深入学习c++

    本来在图书馆借了好几本属,但是,自己没有经验,借的书都太深奥,看不懂,哎,桑心!

  3. 汉字Collection

    只是上一行Demo private static string[] HanZis = new string[]{ "啊阿呵吖嗄腌锕爱矮挨哎碍癌艾唉哀蔼隘埃皑呆嗌嫒瑷暧捱砹嗳锿霭按安暗岸俺案鞍 ...

  4. 第十二章——SQLServer统计信息(4)——在过滤索引上的统计信息

    原文:第十二章--SQLServer统计信息(4)--在过滤索引上的统计信息 前言: 从2008开始,引入了一个增强非聚集索引的新功能--过滤索引(filter index),可以使用带有where条 ...

  5. 一C++PSO(PSO)算法

    收集和变化PSO算法,它可用于参考实施: #include <cstring> #include <iostream> #include <cmath> #incl ...

  6. Gradle多项目配置的一个demo

    ParentProject├─build.gradle├─settings.gradle├─libs├─subProject1├────────────build.gradle├─────────── ...

  7. Codeforces 338D GCD Table 中国剩余定理

    主题链接:点击打开链接 特定n*m矩阵,[i,j]分值为gcd(i,j) 给定一个k长的序列,问能否匹配上 矩阵的某一行的连续k个元素 思路: 我们要求出一个解(i,j) 使得 i<=n &am ...

  8. ARP协议的基础知识

          关于ARP协议的基础知识 1.ARP的工作原理 本来我不想在此重复那些遍地都是的关于ARP的基本常识,但是为了保持文章的完整性以及照顾初学者,我就再啰嗦一些文字吧,资深读者可以直接跳过此节 ...

  9. [Tool]利用Advanced Installer建立x86/x64在一起的安装程式

    原文 [Tool]利用Advanced Installer建立x86/x64在一起的安装程式 之前使用InstallShield做安装程式时,如果要将程式放在Program Files的话,需要分别针 ...

  10. jQuery整理笔记文件夹

    jQuery整理笔记文件夹 jQuery整理笔记一----jQuery開始 jQuery整理笔记二----jQuery选择器整理 jQuery整理笔记三----jQuery过滤函数 jQuery整理笔 ...