我想从RouteTable中检索路由值,但它是null。有人可以帮忙吗?
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"
});
答案 0 :(得分:3)
好的,如果您正在尝试获取当前路线,可以在控制器内执行此操作....
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"];
希望有所帮助。
答案 1 :(得分: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