【问题标题】:ActionFilter is not executing in WebApplication but executing in WebApi动作过滤器不在 Web 应用程序中执行,而是在 Web Api 中执行
【发布时间】:2013-05-19 22:20:57
【问题描述】:

我已经创建了一个 ActionFilterAttribute

public class LoggingNHibernateSessionAttribute : ActionFilterAttribute

过滤器的用途如名称所示,分别在目标操作之前和之后记录并打开和提交事务。

我有一个 WebApi(myAPI) 项目 (MVC4) 和一个 WebApplication(myContent)。

myAPI 中的每个 Api Controller 都使用此属性进行修饰。

using myApp.Web.Common.Filters;

namespace myAPI.Web.Api.Controllers
{
    [LoggingNHibernateSession]
    public class CategoriesController : ApiController
    {

当在 ApiController 中执行 Http 操作(Get/Post)时,ActionFilter 会被执行,并且可以正常工作。

问题: 在 WebApplication(myContent) 中,我还使用 ActionFilter 装饰了这些控制器。

using myApp.Web.Common.Filters;

namespace myContent.Web.Content.Places.Controllers
{
    [LoggingNHibernateSession]
    public class PlacesController : Controller
    {

但是在这里,当一个动作在控制器内部执行时,ActionFilter 并没有被执行。

ActionFilter 属于 System.Web.Http.Filters;

我读过一些帖子,他们说要使用 System.Web.Mvc 过滤器。所以我将 ActionFilter 更改为来自 System.Web.Mvc 当我切换它时,ActionFilter 也停止在 WebApi 中工作。

我在这里做错了什么?

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api action-filter actionfilterattribute


    【解决方案1】:

    尽管 WebApi 和 MVC 非常相似,并且在技术上包含大部分相同的代码,但 WebApi 是通过复制所有代码而不是通过重用来创建的。有人告诉我,这是因为 WCF 团队不希望依赖于 MVC 程序集。

    因此,针对一个程序集编译的代码(例如您的自定义过滤器)将无法在另一个程序集的上下文中工作。

    解决方案是复制您自己的代码并针对两组程序集进行编译。您还可以设置一个构建系统来使用不同的参考程序集交叉编译相同的代码文件。

    当内部公司政治导致这样的事情时,这真是令人难过。他们至少能做的是承认问题并为他们的工具添加一些适当的交叉编译支持,但是,唉,我跑题了。

    【讨论】:

    • 这是我将System.Web.Http.Filters.FilterAttribute 切换为System.Web.Mvc.FilterAttribute 的内容,这解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    相关资源
    最近更新 更多