Route.Defaults 属性

定义

获取或设置要在 URL 不包含所有参数时使用的值。

public:
 property System::Web::Routing::RouteValueDictionary ^ Defaults { System::Web::Routing::RouteValueDictionary ^ get(); void set(System::Web::Routing::RouteValueDictionary ^ value); };
public System.Web.Routing.RouteValueDictionary Defaults { get; set; }
member this.Defaults : System.Web.Routing.RouteValueDictionary with get, set
Public Property Defaults As RouteValueDictionary

属性值

包含参数名称和默认值的对象。

示例

以下示例演示如何创建 Route 对象并设置 ConstraintsDataTokensDefaults 属性。

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
    reportRoute.Defaults = new RouteValueDictionary { { "locale", "en-US" }, { "year", DateTime.Now.Year.ToString() } };
    reportRoute.Constraints = new RouteValueDictionary { { "locale", "[a-z]{2}-[a-z]{2}" }, { "year", @"\d{4}" } };
    reportRoute.DataTokens = new RouteValueDictionary { { "format", "short" } };
    routes.Add(reportRoute);
}
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    RegisterRoutes(RouteTable.Routes)
End Sub

Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
    Dim urlPattern As String
    Dim reportRoute As Route
    
    urlPattern = "{locale}/{year}"
    
    reportRoute = New Route(urlPattern, New ReportRouteHandler)
    reportRoute.Defaults = New RouteValueDictionary(New With {.locale = "en-US", .year = DateTime.Now.Year.ToString()})
    reportRoute.Constraints = New RouteValueDictionary(New With {.locale = "[a-z]{2}-[a-z]{2}", .year = "\d{4}"})
    reportRoute.DataTokens = New RouteValueDictionary(New With {.format = "short"})

    routes.Add(reportRoute)
End Sub

下面的示例演示一个 Route 对象,其 Defaults 属性包含的参数不属于 属性中的 Url 模式。

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
    
    reportRoute.Defaults = new RouteValueDictionary { { "months", "all" } };
    
    routes.Add(reportRoute);
}
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    RegisterRoutes(RouteTable.Routes)
End Sub

Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
    Dim urlPattern As String
    Dim reportRoute As Route
    
    urlPattern = "{locale}/{year}"
    
    reportRoute = New Route(urlPattern, New ReportRouteHandler)
    
    reportRoute.Defaults = New RouteValueDictionary(New With {.months = "all"})
    
    routes.Add(reportRoute)
End Sub

注解

如果 Defaults URL 不包含该参数的段,则属性可用于设置 URL 参数的值。 将 对象分配给 RouteValueDictionary 属性 Defaults 。 对象中的每个 RouteValueDictionary 元素都包含参数的名称以及缺少参数时要使用的值。

可以包含未在 属性中 Url 定义为段的参数的默认值。 当 ASP.NET 路由处理请求时,此默认值始终传递给路由处理程序。 构造 URL 并包含未定义为段的默认参数的值时,仅当提供的值与路由的默认值匹配时,路由才会被视为匹配。

适用于

另请参阅