4

我想从 RouteTable 中检索路由值,但它为空。有人可以帮忙吗?

public static class GetRouteValues
{
    public static string GetSomeValue()
    {
        RouteCollection routes = RouteTable.Routes;
        var value = routes["somevalue"].ToString();
        return value;
    }
}

我想检索此值以在 global.asax 文件中使用,并将某些路由值设置为默认值。

string value = GetRouteValues.GetSomeValue();
routes.MapRoute(null,
                        "{_value}/home",
                        new
                        {
                            _value = value,
                            controller = "home",
                            action = "index"
                        });
4

3 回答 3

5

好的,如果您尝试获取当前路线,则可以从控制器中执行此操作....

var completeRoute = this.ControllerContext.RouteData.Route;
//or
var justValue = this.ControllerContext.RouteData.Values["value"]

让我知道这是否是你所追求的......

更新:

好的,我认为这应该做你所追求的。您应该能够在静态方法中使用它,而无需传入任何上下文对象。

var httpContext = new HttpContextWrapper(HttpContext.Current); 
var requestContext = new RequestContext(httpContext, new RouteData());
var completeRoute = requestContext.RouteData.Route;
var justValue = requestContext.RouteData.Values["value"];

希望有帮助。

于 2010-01-31T21:22:30.090 回答
1

我为我的静态类使用了 anthonyv 的答案,但结果为空。以下对我有用(类似于如何访问静态类中的 Session 对象)。

var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
var action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"];
于 2015-12-21T13:05:20.193 回答
0

Global 会很好,但到目前为止我只在 Controller 中看到过它:

Namespace Controllers
  Public Class HomeController
    Inherits BaseController
      Dim routeValues = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values
      Dim actionName As String
      Dim controllerName As String

      Public Function Index(id As String) As ActionResult
        Try
            Dim x As Integer = 0
            Dim y As Integer = 5
            Dim z As Integer = y / x
        Catch ex As Exception
            If routeValues IsNot Nothing Then
                If routeValues.ContainsKey("action") Then
                    actionName = routeValues("action").ToString()
                End If
                If routeValues.ContainsKey("controller") Then
                    controllerName = routeValues("controller").ToString()
                End If
            End If

            Log.LogError(ex, controllerName, actionName)
        End Try
于 2016-02-24T20:05:00.363 回答