在Web应用程序中的何处以及如何使用拦截器? [英] Where and how to use interceptors in web application?

查看:202
本文介绍了在Web应用程序中的何处以及如何使用拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对拦截器概念感兴趣.我知道这个概念已在NHibernate,Entity Framework等许多库中使用.但是我对如何在ASP.NET MVC Web应用程序中使用此概念感兴趣.

I am interested in interceptor concept in recent times. I know that this concept is used in many libraries like NHibernate, Entity Framework and others. But i am interested in how to use this concept in ASP.NET MVC web application.

在Mvc Web应用程序中有用的地方?

Where it is usefull to use it in Mvc Web application?

有没有使用拦截器的开源Asp.Net Mvc项目?

Is there any open source Asp.Net Mvc project which use interceptors ?

Asp.net Mvc已经支持一种带有过滤器的控制器拦截器.最好使用过滤器而不是拦截器?

Asp.net Mvc already support a kind of interceptor for controller with filters. It is better to use filters instead of interceptors ?

推荐答案

在何处/何时使用拦截器

看看您以前开发的应用程序并检查代码.查找在方法和属性的开头或结尾经常重复的代码.您可能会考虑将此代码从所有这些方法转移到拦截器中.例如,我注意到我执行输入验证的许多MVC动作都是使用相同的几行代码来完成的:

Where/when to use interceptors

Take a look at a previous application you've developed and examine the code. Look for code that is frequently duplicated at the beginning or end of methods and properties. This is code that you may consider moving from all of those methods into an interceptor. For example, I've noticed that many of my MVC actions that perform input validation do so with same same couple lines of code:

if (!ModelState.IsValid)
    return View(model);

这是可能会移动到拦截器(在这种情况下,可能是MVC过滤器)的代码.编写和应用过滤器的成本是否超过了重复代码的成本? (2行代码乘以使用此代码的控制器操作数).在这种情况下,也许不是.但是,在其他情况下,使用拦截器的好处会更大.

This is code that could potentially be moved to an interceptor (probably an MVC filter in this case). Does the cost of writing and applying the filter outweigh the cost of this duplicated code? (2 lines of code times the number of controller actions using this). In this case, perhaps not. There are other situations, however, where the benefit of using an interceptor would be greater.

下面列出了一些我可能会想到的代码重复类型,例如,闻起来像的场景可能会受益于拦截器的场景:

Here's a list of some situations where I imagine this type of code duplication might occur, i.e. scenarios that smell like they could benefit from interceptors:

  • 输入验证(如上所述).
  • 调试日志记录..您可以编写拦截器记录每个方法调用的进入和退出.
  • 线程同步..您的问题是有关Web应用程序的,但是如果您要开发具有MVP样式视图的Windows应用程序,则可以应用拦截器,以确保所有方法调用都同步到UI线程.
  • 数据库事务.我的大多数数据库事务代码如下:
  • Input validation (as illustrated above).
  • Debug logging. You could write an interceptor that records the entrance and exit of every method call.
  • Thread synchronization. Your question is about web apps, but if you're developing a Windows application with an MVP style view, you could apply an interceptor that ensures that all method calls are synchronized back to the UI thread.
  • Database transactions. Most of my database transaction code looks like this:

 

using (var transaction = Session.BeginTransaction())
{
    // ... do some work that is unique to this method ...
    transaction.Commit();
}

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆