【问题标题】:Asp.net Core add several action filters in one filterAsp.net Core 在一个过滤器中添加多个操作过滤器
【发布时间】:2018-11-27 08:03:11
【问题描述】:

我需要创建一个自定义操作过滤器属性,其中包含 2 个“RouteAttibute”过滤器的声明。

我需要:

[Contains2Routes]
public ActionResult Index()
{
    return View();
}

代替:

[Route("~/index1")]
[Route("~/index2")]
public ActionResult Index()
{
    return View();
}

【问题讨论】:

  • 我的回答 here 可能会有所帮助。

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

感谢@Kirk Larkin 和他的回答here,我已经设法解决了这个问题:

public class Contains2RoutesAttribute : Attribute, IActionModelConvention
{

    public void Apply(ActionModel action)
    {
        action.Selectors.Clear();

        // Adding route 1:
        action.Selectors.Add(new SelectorModel
        {
            AttributeRouteModel = new AttributeRouteModel { Template = "~/index1" }
        });

        // Adding route 2:
        action.Selectors.Add(new SelectorModel
        {
            AttributeRouteModel = new AttributeRouteModel { Template = "~/index2" }
        });
    }

}

【讨论】:

  • 酷,我很高兴能帮上忙。在您的情况下,您实际上不需要在此处实现 IResourceFilter,因为您只是在应用路由。
  • @KirkLarkin 太棒了!谢谢!不过我有一个问题,我不能让这个属性与IFilterFactory 一起工作,以便在这个属性中注入一些我需要的服务。当CreateInstance() 方法就位时,Apply() 方法不会被调用。
  • @KirkLarkin - 发布了一个新问题:stackoverflow.com/questions/53525645/…
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2015-05-09
  • 2021-12-31
  • 2017-05-18
  • 1970-01-01
  • 2020-05-12
  • 2016-05-28
  • 1970-01-01
相关资源
最近更新 更多