RouteValueDictionary忽略空值 [英] RouteValueDictionary ignores empty values

查看:104
本文介绍了RouteValueDictionary忽略空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查询字符串中需要几个空路由值:

I have few empty route values I want in the query string:

var routeValues = new RouteValueDictionary();
routeValues.Add("one", "");
routeValues.Add("two", null);
routeValues.Add("three", string.Empty);

如果我随后将其传递给UrlHelper.RouteUrl(),它将忽略所有值,并且生成的查询字符串为空.但是,像/?one=&two=&three=这样的URL完全有效.我该怎么办?

If I then pass it to UrlHelper.RouteUrl() it ignores all the values and the generated query string is empty. However, urls like /?one=&two=&three= are perfectly valid. How can I do that?

推荐答案

此行为内置于默认Route类中.它调用ParsedRoute.Bind()方法进行此检查:

This behavior is built into the default Route class. It calls into the ParsedRoute.Bind() method where it does this check:

if (IsRoutePartNonEmpty(obj2))
{
    acceptedValues.Add(key, obj2);
}

这是哪个:

private static bool IsRoutePartNonEmpty(object routePart)
{
    string str = routePart as string;
    if (str != null)
    {
        return (str.Length > 0);
    }
    return (routePart != null);
}

这样可以有效地防止任何查询字符串值为空时输出.它所做的一切都是私有的,静态的,内部的,否则是无法覆盖的.因此,实际上只有2个选项可以替代此行为.

This effectively prevents any query string values from being output if they are empty. Everything it does is private, static, internal, and otherwise impossible to override. So, there are really only 2 options to override this behavior.

  1. 路由子类并重写GetVirtualPath(),用自定义实现替换ParsedRoute.Bind().
  2. 子类RouteBase并创建自定义路由实现.

我猜第三个选择是将其保留,因为其他人指出这并不是一个真正的问题,因为在查询字符串中有一个空参数几乎没有值.

I guess the 3rd option is to leave it alone, as others have pointed out this isn't really a problem since having an empty parameter in the query string has little or no value.

这篇关于RouteValueDictionary忽略空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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