Retrieve route values ​​from RouteTable

I want to get route values ​​from RouteTable, but it is null. can anyone help?

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

I want to get this value for use in the global.asax file and set the default value for some route value.

string value = GetRouteValues.GetSomeValue();
routes.MapRoute(null,
                        "{_value}/home",
                        new
                        {
                            _value = value,
                            controller = "home",
                            action = "index"
                        });
+3
source share
3 answers

Well, if you are trying to get the current route, you can do it from inside the controller ....

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

Let me know if this is what you are after ...

UPDATE:

Ok, I think this should do what you need. You should be able to use this in a static method without passing in any context object.

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

Hope this helps.

+3
source

anthonyv , . ( ).

var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"];
var action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"];
+1

It would be good globally, but so far I have only seen it in the 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
0
source

Source: https://habr.com/ru/post/1730783/


All Articles