标签:
废话不多话,直接上代码
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"}
标签:
原文地址:http://www.cnblogs.com/zuqing/p/5838014.html