zoukankan      html  css  js  c++  java
  • MVC中Action 过滤

    总结Action过滤器实用功能,常用的分为以下两个方面:

    1、Action过滤器主要功能就是针对客服端请求过来的对象行为进行过滤,类似于门卫或者保安的职能,通过Action过滤能够避免一些非必要的深层数据访问。创建Action过滤的类继承与命名空间Sytem.Web.MVC下的ActionFilterAttribute。举例代码如下:

    public class AdminFilter:ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                //base.OnActionExecuting(filterContext);判断当前用户的Session是不是管理员
                if (!Convert.ToBoolean(filterContext.HttpContext.Session["IsAdmin"]))
                {
                    filterContext.Result = new ContentResult()
                    {
                        Content="Unauthorized to access specified resource"
                    };
                }
            }
        }

    引用该自定义的Action过滤的代码(主要是Action)如下:

           [AdminFilter]
            public ActionResult AddNew()
            {
                EmployeeViewModel myple = new EmployeeViewModel();
                //myple.FooterData = new FooterViewModel();
                //myple.FooterData.CompanyName = "StepByStepSchools";
                //myple.FooterData.Year = DateTime.Now.Year.ToString();
                //myple.UserName = User.Identity.Name; ;
                return View("CreateEmployee", myple);
            }

    2、通过Action请求进行数据的操作。

    场景表述如下:Part分部视图的时候,视图是强数据类型,part中的数据,需要通过每个分页面获取,这个时候,每个分页面都需要定义Part视图需要参数,那么怎么才能不用设置分视图处理这样的数据那?当然继承是一种传播Part视图需要参数的一种方式,但是继承的数据需要实例化。这个时候,我们可以利用Action过滤的方式来完成。ActionFileter代码如下:

    public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                //base.OnActionExecuted(filterContext);
                ViewResult v = filterContext.Result as ViewResult;
                if (v != null)
                {
                    BaseViewModel bvm = v.Model as BaseViewModel;
                    if (bvm != null)
                    {
                        bvm.UserName = HttpContext.Current.User.Identity.Name;
                        bvm.FooterData = new FooterViewModel();
                        bvm.FooterData.CompanyName = "StepByStepSchools";
                        bvm.FooterData.Year = DateTime.Now.Year.ToString();
                    }
                }
            }

    该代码将BaseViewModel进行数据填充,来显示数据。

    Control中Action使用的情况如下:

    [HeaderFooterFilter]
            [Authorize]
            public ActionResult Index()
            {
                            
                EmployeeBusinessLayer empBal = new EmployeeBusinessLayer();
                List<Employee> employees=empBal.GetEmployees();
            ....................................
    }
  • 相关阅读:
    SQL获取分组第一条记录
    Highcharts中Legend动态显示点值
    Json序列化
    Xml 序列化
    Json 用法整理
    Oracle如何复制表的sql语句
    spring.net 如何让xml智能提示
    C# 属性和字段的区别
    EasyUI中Grid标题居中方法(jquery实现方法)
    Asp.net Web.Config
  • 原文地址:https://www.cnblogs.com/xibei666/p/5011372.html
Copyright © 2011-2022 走看看