zoukankan      html  css  js  c++  java
  • Asp.Net MVC在过滤器中使用模型绑定

    废话不多话,直接上代码

     1、创建MVC项目,新建一个过滤器类以及使用到的实体类:

     1     public class DemoFiltersAttribute : AuthorizeAttribute
     2     {
     3         public override void OnAuthorization(AuthorizationContext filterContext)
     4         {
     5             var person = new Person();
     6             //过滤器中使用模型绑定
     7             BindModel<Person>(filterContext, person);
     8             filterContext.Result = new JsonResult() { Data = person, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
     9             //base.OnAuthorization(filterContext);
    10         }
    11 
    12         /// <summary>
    13         /// 模型绑定
    14         /// </summary>
    15         /// <typeparam name="TModel"></typeparam>
    16         /// <param name="model">模型(绑定成功后将会给此赋值)</param>
    17         /// <param name="prefix">获取或设置在呈现表示绑定到操作参数或模型属性的标记时要使用的前缀</param>
    18         public void BindModel<TModel>(AuthorizationContext filterContext, TModel model, string prefix = "") where TModel : class
    19         {
    20             IModelBinder binder = ModelBinders.Binders.GetBinder(typeof(TModel));
    21             ModelBindingContext bindingContext = new ModelBindingContext()
    22             {
    23                 ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
    24                 ModelName = prefix,
    25                 ValueProvider = filterContext.Controller.ValueProvider
    26             };
    27             binder.BindModel(filterContext.Controller.ControllerContext, bindingContext);
    28         }
    29     }
    1     public class Person
    2     {
    3         public int Id { set; get; }
    4         public string Name { set; get; }
    5     }

    继承了AuthorizeAttribute类中的OnAuthorization方法会在执行Action之前执行,具体可以查看我写的这篇文章《Asp.Net MVC过滤器

    2、新建一个控制类,并在控制器贴上DemoFilters特性:

    1     [DemoFilters]
    2     public class HomeController : Controller
    3     {
    4         // GET: Home
    5         public ActionResult Index(Person p)
    6         {
    7             return Content("123");
    8         }
    9     }

    3、访问url:

    http://localhost:8290/home/index?id=1&name=lisi

    输出:{"Id":1,"Name":"lisi"}

  • 相关阅读:
    使用EF批量新增数据十分缓慢
    EF中获取当前上下文的表名
    下拉框停用数据的处理
    CEILING保留n位小数向上取整
    MVC ValidationAttribute 验证一个字段必须大于另一个字段
    EF通过导航属性取出从表的集合后,无法删除子表
    我得新博客上线了采用Vue+Layui的结合开发,后台采用asp.net mvc
    CTS,CLS,CLR解释
    Linq与委托
    C#4.0的十种语法糖
  • 原文地址:https://www.cnblogs.com/zuqing/p/5838014.html
Copyright © 2011-2022 走看看