【问题标题】:Code Cannot hit the Attribute file代码无法命中属性文件
【发布时间】:2016-05-03 20:23:19
【问题描述】:

我想创建日志响应,但是我无法得到结果。 我无法点击 LogResponse 文件。

我有一个文件

public class LogResponse : ActionFilterAttribute

{
    public LogResponse()
    {

    }
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Log("OnActionExecuting", filterContext.RouteData);
        Debug.WriteLine("TEST ");
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Log("OnActionExecuted", filterContext.RouteData);
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Log("OnResultExecuting", filterContext.RouteData);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Log("OnResultExecuted", filterContext.RouteData);
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
        System.IO.StreamWriter file = new System.IO.StreamWriter(@"F:\\test.txt");
        file.WriteLine(message);
        file.Close();
    }
}

现在,我有一个家庭控制器,例如:

[System.Web.Http.AllowAnonymous]
[LogResponse]
public class HomeController : ApiController
{       
    [System.Web.Http.HttpGet]

    public string Index()
    {
        return "Test API";
    }
}

在这里,当我保持调试点时,我可以看到它命中 Index 方法,但它没有命中 Log Response 方法。

我是第一次使用这个。 我也添加了一条路线。在 url 中,我使用 API/Home/Index 进行访问。

谁能告诉我为什么我没有点击我的日志响应文件?

【问题讨论】:

  • 您可能会尝试的第一件事是将类名更改为 LogResponseAttribute。名称上的 Attribute 后缀有点 C# 的魔力。
  • 您使用的是this tutorial 是吗?我个人没有使用过 ActionFiltersAttribute,但我注意到你的方法类型是字符串而不是 ActionResult
  • 你确定你是从正确的ActionFilterAttribute 继承,因为取决于你是在 MVC 还是 WebAPI 上使用它,它应该从 2 个不同命名空间 System.Web.Mvc 上的类继承 MVC 和 @我认为 987654326@ 用于 API。

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

您使用的是 Web API 2。确保您使用的是正确的过滤器:

"Filters for Web API are not the same as filters for MVC. The Web API filters are found in the System.Web.Http.Filters namespace."

And to register the filter:

public static void RegisterWebApiFilters(System.Web.Http.Filters.HttpFilterCollection filters)
{
  filters.Add(new LogRequest());
}

protected void Application_Start()
{
  RegisterWebApiFilters(GlobalConfiguration.Configuration.Filters);
}

【讨论】:

  • 我是这样添加的kernel.Bind<LogResponseAttribute>();
  • 那是忍者,对吧?现在您将其添加到容器中。不会让 Web API 将其用作过滤器。您仍然需要按照我的描述使用 Web API 注册它。
  • 在 LogResponseAttribute.cs 中,我使用的是system.web.mvc,如果我使用其他的,那么它不能覆盖这些方法。
  • 您需要使用其他过滤器。代码会有所不同,但这是您可以与 Web API 一起使用的过滤器。
猜你喜欢
  • 2019-05-02
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 2018-06-15
相关资源
最近更新 更多