【问题标题】:MvcSiteMapProvider MVC5 - Adding "title" as route value not working (intended)MvcSiteMapProvider MVC5 - 添加“标题”作为路由值不起作用(有意)
【发布时间】:2014-07-30 13:42:22
【问题描述】:

我刚刚使用当前的 MvcSiteMapProvider MVC5(来自 nuget,从 MVC4 升级)遇到了一个“问题”。 在创建动态节点时,我曾经在动态节点的 RouteValues 中添加一个路由值“标题” 在我的 DynamicNodeProvider 中。 这在以前的版本中运行良好,但是在尝试此操作时没有出现错误:

An exception of type 'MvcSiteMapProvider.Collections.Specialized.ReservedKeyException' occurred in MvcSiteMapProvider.dll but was not handled in user code

Additional information: The node with key 'someKey' may not add a route value with the key 'title' and value 'someValue' to the RouteValues dictionary because the key is a reserved name. Reserved names are keys that are meant for use internally by MvcSiteMapProvider rather than a dictionary value.

我收到消息,我不应该将“标题”添加为自定义路由参数。 但是,我的完整项目在路由定义中使用“{title}”,我必须将所有内容从标题更改为“{id}”(或其他内容)。

现在我的问题:是否有可能以某种方式将自定义“标题”路由值添加到动态节点?还是根本不可能?

提前致谢!

【问题讨论】:

  • 这可能会有所帮助,看看 MVC 5 路由属性,它们与 MVC 4 stackoverflow.com/questions/21276014/… 不同
  • 感谢您的回复!但是,使用路由属性仍然需要对我的项目进行大量更改,如果可能的话,我更喜欢“更简单”/更快的解决方案:)(即,添加一个“特殊”参数或类似于 DynamicNode 来实现这一点)跨度>
  • 我明白了 - 这是您覆盖 RouteValue 字典中的值的答案stackoverflow.com/questions/13423545/…
  • 感谢您的回复!但不幸的是,这不是我想要的。

标签: asp.net-mvc mvcsitemapprovider


【解决方案1】:

您可以通过继承ReservedAttributeNameProvider 并覆盖IsRouteAttribute 方法来绕过此限制,如下所示。

public class MyReservedAttributeNameProvider
    : ReservedAttributeNameProvider
{
    public MyReservedAttributeNameProvider(
        IEnumerable<string> attributesToIgnore
        ) : base(attributesToIgnore)
    {
    }

    public override bool IsRouteAttribute(string attributeName)
    {
        return attributeName != "visibility"
            && !attributesToIgnore.Contains(attributeName)
            && !attributeName.StartsWith("data-");
    }
}

然后,您可以使用外部 DI 注入新的 ReservedAttributeNameProvider(通过升级到 DI 包之一)。例如,您只需将现有注册替换为您自己的。实现 这就是在 StructureMap 中的样子,但您可以轻松地使用任何其他 DI 容器。

this.For<IReservedAttributeNameProvider>().Use<MyReservedAttributeNameProvider>()
    .Ctor<IEnumerable<string>>("attributesToIgnore").Is(new string[0]);

我建议您长期在 GitHub 上打开 new issue。我想不出为什么必须全面执行这一点——属性名称的这种限制应该只存在于在 XML 中配置节点的情况下,并且在这种情况下不应该有错误消息——只是默默地忽略该值。此外,MvcSiteMapNodeAttribute 具有相同缺陷的事实是从 v3 继承的错误设计决策。应该有一个 RouteValues “字典”(好吧,无论如何是 JSON 字典)来在那里定义值,而不是将所有内容都塞进属性中并试图猜测哪些值去了哪里。但无论哪种方式,从 MvcSiteMapNodeAttribute、动态节点或自定义 ISiteMapNodeProvider 实现中排除任何属性名称都是没有意义的,因为属性不再更新属性,反之亦然。

【讨论】:

  • 谢谢!我想这正是我想要的。我同意你对这个限制的必要性的看法,我想我很快就会开一个新问题。
猜你喜欢
  • 2017-09-29
  • 2014-12-27
  • 2016-01-06
  • 2016-06-28
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-07-20
  • 2018-02-01
相关资源
最近更新 更多