标签:
MVC的每一个请求都会给相应的控制器的对应行为方法处理,那么想在这些处理的前
前后后增加一些额外的逻辑处理,因此过滤器的作用就来了
MVC支持的过滤器类型有四种,分别是:Authorization(授权),Action(行
为),Result(结果)和Exception(异常)
下面试一个小例子:
控制器:
public class FilterDemoController : Controller
{
//
// GET: /FilterDemo/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string name)//添加视图
{
ViewBag.name = name;
Response.Cookies["name"].Value = name;
return View();
}
[MyFilterAttribute]
public ActionResult List()
{
ViewBag.name = Request.Cookies["name"].Value;
return View();
}
}
-----
Index视图:
<div>
<h1>这是首页 @ViewBag.name</h1>
<hr />
@Html.ActionLink("goto List...", "list")
<br />
<form action="/FilterDemo/index" method="post">
<input id="name" name="name" type="text" />
<input id="Submit1" type="submit" value="登录" />
</form>
</div>
-------MyFilterAttribute 过滤器是一个*.cs后缀的文件,也就是一个类
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{
base.OnActionExecuting(filterContext);
HttpContextBase context = filterContext.HttpContext;
if (context.Request.Cookies["name"] == null)
{
//失败,跳转,日志就不记录了(有时候失败了也要记录一次)
context.Response.Redirect("/FilterDemo/index");
}
//日志记录
string msg = context.Request.Cookies["name"].Value + "用户" +
DateTime.Now.ToString() + "访问了" + context.Request.RawUrl + "地址\r\n";
FileInfo info = new FileInfo("d:/log.txt");
StreamWriter sw = info.AppendText();
sw.Write(msg);
sw.Flush();
sw.Dispose();
}
-----当然List方法也要添加一个视图。
标签:
原文地址:http://www.cnblogs.com/wangxlei/p/5982868.html